令人惊讶的是,我在网上找不到任何相关信息。也许我错过了什么。您如何使用 CSS Grid 水平和垂直居中整个主包装器,并且显然保持响应能力?
.wrapper {
display: grid;
grid-template-columns: minmax(100vw, 1fr);
grid-template-rows: minmax(100vh, 1fr);
align-items: center;
justify-content: center;
}
<div class="wrapper">
<div class="centerthis">loremloremlorem</div>
</div>
使用上面的 CSS,
div
垂直居中,但不是水平居中。
以下 CSS 将 div 水平居中,但不是垂直居中:
.maingrid {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
align-items: center;
justify-content: center;
}
.centerthis {
align-self: center;
justify-self: center;
}
<div class="maingrid">
<div class="centerthis">loremloremlorem</div>
</div>
代替
justify-content: center
使用justify-items: center
.
.wrapper {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 100vh;
align-items: center;
justify-items: center; /* adjusted */
}
<div class="wrapper">
<div class="centerthis">loremloremlorem</div>
</div>
在你的第二个例子中,你说:
以下 CSS 将 div 水平居中而不是垂直居中。
那是因为容器没有额外的高度。行是内容的高度。而不是
grid-template-rows: 1fr
尝试像grid-template-rows: 100vh
.
.maingrid {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 100vh;
align-items: center;
justify-content: center;
}
.centerthis {
align-self: center;
justify-self: center;
}
body {
margin: 0;
}
<div class="maingrid">
<div class="centerthis">loremloremlorem</div>
</div>
更多在这里:
而不是使用
align-items: center;
justify-items: center;
你可以使用
place-items: center;
.wrapper {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 100vh;
place-items: center;
border: 2px solid;
}
<div class="wrapper">
<div class="centerthis">loremloremlorem</div>
</div>
2x2 网格中 4 个项目的示例。
如果你想让你的物品在外容器内变小;将
width: 100%
更改为您喜欢的任何内容,并在您的 CSS 中添加 margin-top:
和 margin-left:
(例如:width: 70%
、margin-top: 15%
、margin-left: 15%
。边距是剩余空间的一半,以保持居中)
#wrapper {
position: absolute;
display: grid;
width: 100%;
grid-template-columns: 1fr 1fr;
}
<div id="wrapper">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
只在 "wrapper" 类中添加 margin auto ,像这样
margin: 0 aunto;
有了这个,你可以将容器(包装器)相对于它的直接父级(通常是“body”)居中
希望对你有帮助,
如果你这样做更好
.wrapper {
display: flex;
flex-direction: row; // Not really necassary though
justify-content: center; // Or you could use "space-around"
align-items: center;
}
我建议你使用flex-box,它是CSS3中新的布局模式。
在这种情况下,我们只需给 .maingrid display: flex 一个高度并将内容居中。
然后让 .centerthis 对齐到他父亲元素的中间,如下所示。
希望对你有帮助,
.maingrid {
display: flex;
height: 100px;
justify-content: center;
}
.centerthis {
align-self: center;
}
<div class="maingrid">
<div class="centerthis">loremloremlorem</div>
</div>