Html 使用固定宽度的列在CSS网格中居中
我试图做一个简单的以CSS为中心的网格布局。 我知道,当我使用Html 使用固定宽度的列在CSS网格中居中,html,css,css-grid,centering,Html,Css,Css Grid,Centering,我试图做一个简单的以CSS为中心的网格布局。 我知道,当我使用justify items:center时,网格容器中的项目应该水平对齐,但是当我像这样指定像素列宽网格模板列:repeat(3100px)时,整个网格将恢复正常。那么,有没有办法使网格项居中,但同时以像素为单位指定列宽? 以下是我的例子: <div class="container"> <div class="item"></div> <div cla
justify items:center
时,网格容器中的项目应该水平对齐,但是当我像这样指定像素列宽网格模板列:repeat(3100px)
时,整个网格将恢复正常。那么,有没有办法使网格项居中,但同时以像素为单位指定列宽?
以下是我的例子:
<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>
将
justify items
更改为justify content
,它应该可以工作
.container{
背景色:#aa96da;
显示:网格;
/*证明项目:中心*/
证明内容:中心;
栅隙:20px;
网格模板行:重复(3,1fr);
/*只有当我将此100px更改为“1fr”时,调整项才能工作*/
网格模板列:重复(3100px);
}
.项目{
宽度:100px;
高度:100px;
背景颜色:绿色;
}
简短回答:您希望
调整内容
而不是调整项目
.container{
背景色:#aa96da;
显示:网格;
对齐内容:居中;/*-项到-内容*/
栅隙:20px;
网格模板行:重复(3,1fr);
/*只有当我将此100px更改为“1fr”时,调整项才能工作*/
网格模板列:重复(3100px);
}
.项目{
宽度:100px;
高度:100px;
背景颜色:绿色;
}
如何将宽度为100px的项目居中放置在宽度相同的列中?没有居中的空间我想要的是将整个网格容器居中,而不是特定网格中的项目哦,谢谢,完全修复了它!再读两遍你的答案后,我终于明白了网格布局是如何工作的,以及justify items
和justify content
的意思。@Adolin如果你想要更深入的解释的话
.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;
}