html - 如果存在 1 或 2 个 div,则在最后一行水平自动居中 div 内容

标签 html css

好吧,我有一个奇怪的请求要尝试实现。我有一个包含 div 列表的页面,其中有一个图像和一个链接。每行最多有 3 个 div。但有时,最后一行可能只有 1 或 2 个 div。我需要尝试做的是进行设置,以便如果最后一行只有 1 或 2 个 div,则这些 div 需要在其行内水平居中。

这是可能的吗?我是否需要使用 JavaScript/jQuery 来计算最后一行中的 div 数量?或者我可以仅使用 CSS 来完成这一切吗?

现在 div 是这样设置的:

  <div class="About-Categories clearfix">
    <div class="About-Category clearfix">
        <img src="[image url]" class="image">
        <a href="#">[link text]</a>
     </div>
     <!--Additional About-Category divs go here as needed-->
  </div>

可以有任意数量的关于类别 div,但设置 css 以确保页面宽度内只有 3 个关于类别 div(直到达到 460 像素的屏幕尺寸)。

现在的 CSS:

.About-Categories{
  text-align: center;
}
.About-Category{
  float: left;
  height: auto;
  margin-left: 0%;
  margin-top: 0px;
  display:inline-block;
  padding: 30px;
  width: 33%;
  &:nth-of-type(1){
    clear: both;
  }
}

最佳答案

#wrap { 
    width: 600px;
    text-align: center;
}
.tile {
    width: 198px;
    height: 100px;
    border: 1px solid #000;
    display: inline-block;
    margin: 0;
    padding: 0;
}
<div id="wrap">
<div class="tile"></div><div class="tile"></div><div class="tile"></div><div class="tile"></div><div class="tile"></div>
</div>

关于html - 如果存在 1 或 2 个 div,则在最后一行水平自动居中 div 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458139/

相关文章:

html - 如何实现2行+1列的网格布局

html - .htaccess 导致 apache 不显示页面但下载它们

html - Chrome 中的按钮填充

javascript - 如何使用 jquery 更改 html 中的背景颜色

jQuery .toggle() 使按钮消失

html - 是否有可能存在有效但不可见的溢出?

html - 如果没有 "padding-cheat",我的标题如何居中?

javascript - 背景图像不会在滚动时保持固定

javascript - 需要帮助以 html 形式对齐动态 td 元素

html - 仅在换行上使用文本缩进