如何垂直居中div元素



我想用CSS将div垂直居中。我不想要表格或JavaScript,但只有纯CSS。我找到了一些解决方案,但是它们都不支持ie6。

您可以通过多种方式做到这一点。我将从网格开始,因为我喜欢网格。CSS Grid Layout擅长将页面划分为主要区域,或者根据大小、位置和层定义控件各部分之间的关系,这些都是由HTML原语构建的。网格布局允许作者将元素对齐到列和行中。如果您希望元素中包含的所有元素垂直居中,您可以在父元素上使用属性display: grid;,然后在属性align-items: center;之后使用。例如,请参阅以下代码:

section {
height: 90vh;
width: 100%;
background-color: blue;
display: grid;
align-items: center;
}
div {
height: 100px;
width: 100px;
background-color: brown;
}
<section>
<div></div>
</section>

如果您想为每个元素指定特定的对齐方式,您可以避免为父元素指定属性align-items: center;,并直接对其包含的每个元素使用属性align-self: center;。请看下面的例子:

section {
height: 90vh;
width: 100%;
background-color: blue;
display: grid;
}
div {
height: 100px;
width: 100px;
background-color: brown;
align-self: center;
}
<section>
<div></div>
</section>

另一种方法是通过使用flexx。原理是差不多的。您可以应用一个适用于所有包含元素的规则:

section {
height: 90vh;
width: 100%;
background-color: blue;
display: flex;
align-items: center;
}
div {
height: 100px;
width: 100px;
background-color: brown;
}
<section>
<div></div>
</section>

或指定每个的位置:

section {
height: 90vh;
width: 100%;
background-color: blue;
display: flex;
}
div {
height: 100px;
width: 100px;
background-color: brown;
align-self: center;
}
<section>
<div></div>
</section>

如果你想了解更多关于这些主题,我给你留下了我学习它们的网站链接:https://developer.mozilla.org/en-US/docs/Learn

我希望我有帮助!

最新更新