已知元素宽高
margin负值 + 绝对定位
优点:兼容性好。
缺点:需提前知道元素的尺寸,否则需借助JS获得。
.child {
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
calc + 绝对定位
缺点:兼容性差
.parent {
position: relative;
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
}
.child {
width: 60px;
height: 50px;
background: #19be6b;
position: absolute;
left: calc(50% - 30px);
top: calc(50% - 25px);
}
未知元素宽高
transform + 绝对定位
优点:不需知道元素尺寸
缺点:兼容性不好,只支持IE9+
.child {
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
}
margin:auto + 绝对定位
优点:兼容性好,不需知道元素尺寸
缺点:不支持IE7以下的浏览器
.element {
width: 600px; height: 400px;
position: absolute; left: 0; top: 0; right: 0; bottom: 0;
margin: auto; /* 有了这个就自动居中了 */
}
:before伪类 + vertical-align: middle
优点:兼容性好,不需知道元素尺寸
理解:before伪类搭配vertical-align:middle实现垂直居中的原理
.parent {
display: inline-block;
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
text-align: center;
}
.parent:before {
display: inline-block;
width: 20px;
height: 100%;
content: '';
background: #ff9900;
vertical-align: middle;
}
.child {
display: inline-block;
width: 50px;
height: 50px;
background: #19be6b;
vertical-align: middle;
}
line-heihgt + vertical-align: middle
.parent {
width: 300px;
height: 300px;
font-size: 0;
line-height: 300px;
background: #80848f;
text-align: center;
}
.child {
display: inline-block;
width: 60px;
height: 50px;
background: #19be6b;
vertical-align: middle;
}
table-cell
.parent {
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 60px;
height: 50px;
background: #19be6b;
display: inline-block;
vertical-align: top;
}
flex
缺点:兼容性差
.parent {
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
display: -webkit-flex; /* Safari */
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 60px;
height: 50px;
background: #19be6b;
}
/* or */
.parent {
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
display: -webkit-flex; /* Safari */
display: flex;
}
.child {
width: 60px;
height: 50px;
background: #19be6b;
margin: auto;
}
grid
/* or */
.parent {
width: 300px;
height: 300px;
font-size: 0;
background: #80848f;
display: grid;
}
.child {
width: 60px;
height: 50px;
background: #19be6b;
margin: auto;
}
writing-mode
优点:居中元素不需要设置宽高, 兼容ie8
缺点: 必须要有文字,有局限性
<style>
.center-box{
writing-mode: tb-lr;
writing-mode: vertical-lr;
text-align: center;
}
.center-wrap{
writing-mode: lr-tb;
writing-mode: horizontal-tb;
text-align: center;
width: 100%;
display: inline-block;
}
.center-content{
display: inline-block;
text-align: left;
text-align: initial;
}
</style>
<div class="center-box">
<div class="center-wrap">
<div class="center-content">
你想要上下左右居中的内容(元素,文本或其任意组合)
</div>
</div>
</div>