CSS 中实现水平垂直居中的方法很多,各有优缺点。下面就为大家一一介绍,完整代码可以查看Demo
flex 方案
.parentElement {
display: flex;
justify-content: center;
align-items: center;
}
强烈推荐,几行代码即可实现。查看Demo
grid 方案
.parentElement {
display: grid;
}
.childElement {
align-self: center;
justify-self: center;
}
和 flex 一样,代码量少,不过兼容性不如 flex。查看Demo
transform 方案
.childElement {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
将 translate 设置为-50%,即可实现居中。查看Demo
table 方案
.parentElement {
text-align: center;
}
.childElement {
display: inline-block;
}
tabel 自带垂直居中,只要添加一个水平居中属性即可。缺点:HTML 代码冗余,也不是 table 的正确用法。查看Demo
table-cell 方案
.parentElement {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.childElement {
display: inline-block;
}
和 table 相同的效果,没有那么多的冗余代码。查看Demo
lineheight 方案
.parentElement {
line-height: 600px;
text-align: center;
}
.childElement {
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left;
}
将子元素设为行内元素,通过 text-align 实现水平居中,vertical-align 实现垂直居中。查看Demo
absolute + 负margin 方案
.childElement {
position: absolute;;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
由于绝对定位是基于子元素左上角,将外边距设为子元素宽高一半的负值,即可实现居中。查看Demo
absolute + margin auto 方案
.childElement {
background: red;
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
将各方向的距离均设为0,再将 margin 设为 auto,即可居中。查看Demo
absolute + calc 方案
.childElement.size {
position: absolute;;
top: calc(50% - 100px);
left: calc(50% - 100px);
}
减去宽度的一半即可实现居中。查看Demo
writing-mode 方案
.parentElement {
writing-mode: vertical-lr;
text-align: center;
}
.parentElement-inner {
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
width: 100%;
}
.childElement {
display: inline-block;
margin: auto;
text-align: left;
}
writing-mode 可以将文字改为垂直方向显示,其他水平方向上的也会变为垂直方向上的属性。该方法较为复杂。查看Demo
总结
无兼容性要求,推荐使用 flex 方案
有兼容性要求,且宽高固定,可使用 absolute + 负margin 方案
有兼容性要求,宽高不固定,可使用 css-table 方案