<分区>
<分区>
尝试在 div 中垂直居中标题时遇到了一些麻烦。 CSS 如下:
.container {
background: #a3f;
padding-left: 3% !important;
}
.container h4 {
vertical-align: middle;
text-align: center;
background: #f02;
}
最佳答案
我有几 (5) 种方法:
网格
(使用网格的两种方式).container {
background: #a3f;
height: 100px;
display: grid;
place-items: center;
/* or */ /* place-content: center; */
}
.container h4 {
background: #f02;
}
<div class="container">
<h4> The header </h4>
</div>
flex
.container {
background: #a3f;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
.container h4 {
background: #f02;
}
<div class="container">
<h4> The header </h4>
</div>
翻译(-50%, -50%)
.container {
background: #a3f;
height: 100px;
position: relative;
}
.container h4 {
background: #f02;
position: absolute;
left: 50%; top: 50%;
margin: 0; padding: 0;
-ms-transform: translate(-50%, -50%);
transform : translate(-50%, -50%);
}
<div class="container">
<h4> The header </h4>
</div>
表格
.container {
background: #a3f;
height: 100px;
width: 100%;
display: table;
text-align: center;
}
.container h4 {
display: table-cell;
vertical-align: middle;
}
<div class="container">
<h4> The header </h4>
</div>
transform: translateY(-50%);
with position: relative;
.container {
background: #a3f;
height: 100px;
}
.container h4 {
background: #f02;
text-align: center;
position: relative;
top: 50%;
transform: translateY(-50%);
}
<div class="container">
<h4> The header </h4>
</div>
关于html - 不能在div中垂直居中h1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443042/