使用 CSS-Grid,我尝试将我的元素放在网格单元格的中心,而不是将它们完全缩小到只有内容。这可能吗?
我在 stackblitz 上做了一个简单的例子。您可以看到那里的元素没有用背景色填充整个网格单元格。让它工作的正确方法是什么?我可以删除 justify-items/align-items 类,但内容不再居中。
https://stackblitz.com/edit/angular-8bggtq?file=app/app.component.html
单元格已填充,但内容不在中心:
单元格未填充,但内容居中:
.wrapper {
display: grid;
height: 100vh;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
justify-items: center;
align-items: center;
}
.item {
//justify-self: stretch;
//align-self: stretch;
}
.one {
background: red;
}
.two {
background: pink;
}
.three {
background: violet;
}
.four {
background: yellow;
}
.five {
background: brown;
}
.six {
background: green;
}
html,
body {
margin: 0;
}
<div class="wrapper">
<div class="item one">1</div>
<div class="item two">2</div>
<div class="item three">3</div>
<div class="item four">4</div>
<div class="item five">5</div>
<div class="item six">6</div>
</div>
网格容器的 HTML 结构有三个层次:
- 容器
- 元素(容器的子项)
- 内容(容器的孙代和元素的子代)
您遇到的问题是您采用的是两级方法,而不是正确的三级方法。当您在容器上设置 align-items
和 justify-items
时,它们适用于网格元素,不适用于内容。
这正是您所看到的:网格元素垂直和水平居中。
如果你想将网格元素子项(内容)居中,你需要在元素上指定。您可以对元素重复您对容器所做的操作:
.item {
display: grid;
justify-items: center;
align-items: center;
}
或者,如果您不需要元素中的网格布局,这是另一种简单的方法:
.item {
display: flex;
justify-content: center;
align-items: center;
}
上述概念也适用于 flex 容器。
有关更完整的解释和其他居中方法,请参阅此帖子:Centering in CSS Grid
.wrapper {
display: grid;
height: 100vh;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
}
.item {
display: flex;
align-items: center;
justify-content: center;
}
.one { background: red; }
.two { background: pink; }
.three { background: violet; }
.four { background: yellow; }
.five { background: brown; }
.six { background: green; }
body { margin: 0; }
<div class="wrapper">
<div class="item one">1</div>
<div class="item two">2</div>
<div class="item three">3</div>
<div class="item four">4</div>
<div class="item five">5</div>
<div class="item six">6</div>
</div>