我有一些瓦片,在一些容器内都是相同的静态宽度和高度。容器的宽度是动态的。瓷砖的数量是动态的。我需要将瓷砖“包裹”,以便尽可能多地适合每一行,但是当瓷砖的数量填满容器的宽度时会创建一个新行。一整排瓷砖应居中。一排未满的图 block 应与一整行左对齐(或定位为好像它已满并居中)。请参见下图。
在此图中,绿色代表容器,黑色代表瓦片。
我可以通过制作瓦片 inline-block
并在容器上使用 text-align: center
来接近。但是,结果如下所示:
这是一个代码示例。我能够对 HTML 进行必要的更改。
.container {
border: 5px solid #0f0;
width: 250px;
text-align: center;
}
.tile {
margin: 3px;
display: inline-block;
border: 5px solid #000;
width: 50px;
height: 40px;
}
<div class="container">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
最佳答案
长话短说
有一种方法可以使用 CSS Grid Layout .必须将以下属性放在父元素中,在这种情况下是 .container
元素:
display: grid;
grid-template-columns: repeat(auto-fill, 60px);
grid-gap: 10px;
justify-content: center;
一些解释和细节
我已经尝试了很多来使这项工作成功,但最后我只成功地使用了我在这里第一次使用的 CSS 网格布局。我敢打赌有更多的读者对上述属性不是很熟悉,所以我会为每个属性添加一两行解释。
display: grid;
除了browser support中的限制外,这没什么好说的。 .
grid-template-columns: repeat(auto-fill, 60px);
The grid-template-columns CSS property defines the line names and track sizing functions of the grid columns.
这个属性有点复杂,因为它的值有很多不同的选项。这里我们使用 repeat()该函数需要列数作为第一个参数,每个列单元格的宽度作为第二个参数。幸运的是,可以使用 auto-fill
定义可变列号。 60px
的宽度是.tile
的宽度(宽度50px,边框10px)
grid-gap: 10px;
The grid-gap CSS property is a shorthand property for grid-row-gap and grid-column-gap specifying the gutters between grid rows and columns.
要为列和行定义不同的间隙宽度,您可以使用 grid-gap: 5px 10px;
其中第一个值是行间隙。我为这个例子随机选择了 10px
。
justify-content: center;
最后,如果周围有空间,让我们告诉浏览器将容器(网格)的内容居中。此属性与 CSS 网格布局无关。它通常用于 flexbox 场景,但在这里也很有用。
演示
我将描述的四个属性添加到 .container
并从 .tile
中删除边距和宽度。在 Firefox 52 和 Chrome 57 中测试的解决方案。
.container {
border: 5px solid #0f0;
width: 250px;
display: grid;
grid-template-columns: repeat(auto-fill, 60px);
grid-gap: 10px;
justify-content: center;
}
.tile {
display: inline-block;
border: 5px solid #000;
height: 40px;
}
<div class="container">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
很高兴知道
在 FF 开发人员控制台 (F12) 中有一个内置的网格高亮器,可以轻松调试定义的网格:
关于css - 动态列数,全部居中,内部左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43356537/