一、利用绝对定位
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: red;
}
</style>
二、利用flex布局设置居中
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
align-items: center; // 纵轴对齐方式,默认是纵轴 子元素垂直居中
justify-content: center; //纵轴对齐方式,默认是纵轴
}
.child {
background: red;
}
</style>
三、flex给子项设置
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
}
.child {
background: red;
margin: auto; // 水平垂直居中
}
</style>
四、给容器加给伪元素
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
}
.box::after {
content: "";
line-height: 200px;
}
.child {
display: inline-block;
background: red;
}
</style>
五、tabel-cell实现垂直居中
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: table-cell;
vertical-align: middle; // 设置元素在垂直方向上的对齐方式
text-align: center;
}
.child {
background: red;
display: inline-block;
}
</style>
六、利用grid设置居中
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
align-items: center;
justify-content: center;
}
.child {
background: red;
}
</style>
七、grid给子项设置
<div class="box">
<div class="child">水平垂直居中</div>
</div>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
}
.child {
background: red;
margin: auto;
}
</style>