這裏的demo都只是針對現代瀏覽器所做,未兼容低版本的IE以及其它非主流瀏覽器。
1.使用絕對定位和負外邊距對塊級元素進行垂直居中
<div id="box">
<div id="child">我是測試DIV</div>
</div>
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 200px;// 或者是百分比
height: 100px;
background: orange;
position: absolute;
top: 50%;
left: 50%
margin: -50px 0 0 -100px;
}
注意: 這個方法兼容性不錯,但是有一個小缺點:必須提前知道被居中塊級元素的尺寸,否則無法準確實現垂直居中。*
2. 使用絕對定位和transform
<div id="box">
<div id="child">我是測試DIV</div>
</div>
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
background: #93BC49;
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
}
注意:這種方法有一個非常明顯的好處就是不必提前知道被居中元素的尺寸了,因爲transform中translate偏移的百分比就是相對於元素自身的尺寸而言的。
3. 絕對定位結合margin: auto
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 200px;
height: 100px;
background: #A1CCFE;
position: absolute;
top: 0;
left:0;
right:0;
bottom: 0;
margin: auto;
line-height: 100px;
}
4. 使用flex佈局
<div id="box">
<div id="child">
程序員怎麼才能保護好眼睛?
</div>
</div>
#box {
width: 300px;
height: 300px;
background: #ddd;
display: flex;
align-items: center;
justify-content: center;
}
#child {
width: 300px;
height: 100px;
background: #8194AA;
line-height: 100px;
}
flex佈局(彈性佈局/伸縮佈局)里門道頗多,這裏先針對用到的東西簡單說一下,想深入學習的小夥伴可以去看阮一峯老師的博客。(http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html)
flex也就是flexible,意爲靈活的、柔韌的、易彎曲的。
元素可以通過設置display:flex;將其指定爲flex佈局的容器,指定好了容器之後再爲其添加align-items屬性,該屬性定義項目在交叉軸(這裏是縱向軸)上的對齊方式,可能的取值有五個,分別如下:
flex-start::交叉軸的起點對齊;
flex-end:交叉軸的終點對齊;
center:交叉軸的中點對齊;
baseline:項目第一行文字的基線對齊;
stretch(該值是默認值):如果項目沒有設置高度或者設爲了auto,那麼將佔滿整個容器的高度。