絕對(duì)定位實(shí)現(xiàn)垂直水平居中
優(yōu)點(diǎn):兼容性好
缺點(diǎn):需要知道寬高鳖悠,不夠靈活
<div class="box">
<div class="txt">已知寬高</span>
</div>
.txt{
width: 600px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -200px;
margin-left: -300px;
}
transform實(shí)現(xiàn)垂直水平居中
優(yōu)點(diǎn):不需要知道寬高,靈活
缺點(diǎn):兼容性不好溶锭,在Mobile設(shè)備上建議使用
<div class="box">
<div class="txt">未知寬高</span>
</div>
.txt{
width: 600px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
margin:auto實(shí)現(xiàn)垂直水平居中
優(yōu)點(diǎn):靈活且兼容性好(IE8+)
缺點(diǎn):適用于有尺寸的元素宝恶。
<div class="box">
<div class="txt">已知寬高</span>
</div>
.txt{
width: 600px;
height: 400px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
原理:
先把margin:auto; width:600px; height:400px;干掉后,你會(huì)驚奇的發(fā)現(xiàn)趴捅,.txt 鋪滿了整個(gè).box垫毙。這是為什么呢?
先看下剩余屬性:left,right,top,bottom拱绑,文檔說(shuō)明的很清楚综芥,比如:left值,就是元素的左邊緣距離父元素左邊緣的距離猎拨。當(dāng)left-right 兩個(gè)值同時(shí)存在且都為0膀藐,top-bottom兩個(gè)值也同時(shí)存在且都為0。子元素.txt只能左右上下鋪滿整個(gè).box迟几。
再看下margin:auto消请。它的填充規(guī)則和普通流體元素一模一樣:
- 如果一側(cè)定值,一側(cè)auto, auto為剩余空間大小
- 如果兩側(cè)為auto, 則平分剩余空間类腮。
flexbox 實(shí)現(xiàn)垂直水平居中
優(yōu)點(diǎn):不需要知道寬高臊泰,靈活
缺點(diǎn):兼容 性不好,在Mobile設(shè)備上建議使用
<div class="box">
<div class="txt">未知寬高</span>
</div>
.box{
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
justify-content: center;
align-items: center;
}
table 實(shí)現(xiàn)垂直水平居中
優(yōu)點(diǎn):兼容性好
<div class="box">
<span class="txt">這里顯示多行文字</span>
</div>
.box{
width:500px;
height:500px;
border:1px solid red;
display: table-cell;
vertical-align:middle;
}
.box .txt{
display:inline-block;
}