我正在尝试制作一个简单的以 CSS 为中心的网格布局。
我知道当我使用 justify-items: center
,网格容器内的元素应该水平对齐,但是当我像这样以像素为单位指定列宽时 grid-template-columns: repeat(3, 100px)
整个电网恢复正常。那么有什么方法可以使网格项居中但同时以像素为单位指定列宽?
这是我的例子:
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
.container {
background-color: #aa96da;
display: grid;
justify-items: center;
grid-gap: 20px;
grid-template-rows: repeat(3, 1fr);
/*Only if I change this 100px to '1fr' the justify-items will work */
grid-template-columns: repeat(3, 100px);
}
.item {
width: 100px;
height: 100px;
background-color: green;
}
最佳答案
更改 justify-items
至 justify-content
它应该工作。
.container {
background-color: #aa96da;
display: grid;
/* justify-items: center; */
justify-content: center;
grid-gap: 20px;
grid-template-rows: repeat(3, 1fr);
/*Only if I change this 100px to '1fr' the justify-items will work */
grid-template-columns: repeat(3, 100px);
}
.item {
width: 100px;
height: 100px;
background-color: green;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
关于html - 使用固定宽度的列在 CSS 网格中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61492613/