尝试在div中垂直放置标题时遇到麻烦。 CSS如下:
.container {
background: #a3f;
padding-left: 3% !important;
}
.container h4 {
vertical-align: middle;
text-align: center;
background: #f02;
}
答案 0 :(得分:1)
也许正在使用flexbox?
.container {
background: #a3f;
padding-left: 3% !important;
height: 500px;
display:flex;
justify-content:center;
align-items:center;
}
.container h4 {
/*vertical-align: middle;*/
text-align: center;
background: #f02;
}
<div class="container">
<h4>Blabla</h4>
</div>
答案 1 :(得分:1)
我有几种(5)方法:
grid
(使用网格的两种方式)
.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>
translate(-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>
table
.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%);
与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>