可组合水平居中 + 垂直居中进行配置
1 居中文本
1.1 居中单行文本
1.1.1 text-align: center; line-height=height
<div style="text-align: center; height: 100px; line-height: 100px; background-color: #F2C679;">
水平垂直居中
</div>
效果
水平垂直居中
1.2 居中多行文本
1.2.1 display: flex; align-items: center; justify-content: center; text-align: center;
<div style="display: flex; align-items: center; height: 200px; justify-content: center; text-align: center; background-color: #F2C679;">
水平垂直居中<br />水平垂直居中水平垂直居中水平垂直居中<br />水平垂直居中水平垂直居中
</div>
效果
水平垂直居中
水平垂直居中水平垂直居中水平垂直居中
水平垂直居中水平垂直居中
水平垂直居中水平垂直居中水平垂直居中
水平垂直居中水平垂直居中
2 居中自身
无
3 居中子元素
3.1 单个子元素
3.1.1 display: flex; align-items: center; justify-content: center;
同时适用于“居中多个子元素”。见3.2.1
<div style="height: 200px; display: flex; align-items: center; justify-content: center; background-color: #F2C679;">
<div style="height: 60px; background-color: #e8952e;">水平垂直居中</div>
</div>
效果
水平垂直居中
3.2 多个子元素
3.2.1 display: flex; align-items: center; justify-content: center;
同时适用于“居中单个子元素”。见3.1.1
<div style="height: 200px; display: flex; align-items: center; justify-content: center; background-color: #F2C679;">
<div style="height: 60px; background-color: #e8952e;">水平垂直居中</div>
<div style="height: 40px; background-color: #ea390f;">水平垂直居中</div>
<div style="height: 80px; background-color: #e8952e;">水平垂直居中</div>
</div>
效果
水平垂直居中
水平垂直居中
水平垂直居中
3.2.2 (父)text-align: center; + ::before + (子)display: inline-block; vertical-align: middle;
<style>
.demo-container1 {
width: 400px;
height: 400px;
text-align: center;
background-color: #f2c679;
}
.demo-container1::before {
content: "";
width: 0;
height: 100%;
display: inline-block;
position: relative;
vertical-align: middle;
}
.demo-box-a1 {
text-align: left;
width: 80px;
height: 100px;
display: inline-block;
vertical-align: middle;
background-color: #e8952e;
}
.demo-box-b1 {
width: 80px;
height: 300px;
display: inline-block;
vertical-align: middle;
background-color: #ea390f;
}
.demo-box-c1 {
width: 80px;
height: 200px;
display: inline-block;
vertical-align: middle;
background-color: #e8952e;
}
</style>
<div class="demo-container1">
<div class="demo-box-a1">居中</div>
<div class="demo-box-b1">居中</div>
<div class="demo-box-c1">居中</div>
</div>
效果
居中
居中
居中