有没有从中心填充网格的方法?
我有一个CSS网格容器,它有一个动态内容(它会被更新,所以子级的数量不是固定的),如下所示:
#container {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
}
如果我填满了所有的4列,它会是这样的:
1 2 3 4 //Numbers that represent containers children
这对我来说还可以,但是当我的主容器中只有两个div时,问题就来了,然后它看起来像这样:
1 2 0 0
我希望达到的目标是:
0 1 2 0
对于网格,不可能将动态数量的元素居中。 网格布局适用于元素数量固定的布局。
请参考网格与flex布局的使用。 您的问题更适合由flex解决,在flex容器上使用justify-content:center
来实现居中的子项。
要实现子级居中,请修改#container
div上的样式:
#container {
display: flex;
justify-content: center;
}
您需要0 1 0 0
,0 1 1 0
,0 1 1 1
,1 1 1 1
且假设只有四列的场景:
.container {
display: flex;
justify-content: center;
}
.col {
width: 25%;
height: 50px;
background: green;
}
.col:last-child:not(:nth-child(even)):first-child {
margin-left: -25%;
}
.col:last-child:not(:nth-child(even)):not(:first-child) {
margin-right: -25%;
}
我假设您的标记是这样的:
<div class="container">
<div class="col">
Col
</div>
<!-- Other Columns Go Here -->
</div>
工作小提琴