編碼的世界 / 優質文選 / 生涯

CSS 元素垂直居中的 6種方法


2021年9月20日
-   

轉自:http://blog.zhourunsheng.com/2012/03/css-%E5%85%83%E7%B4%A0%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD%E7%9A%84-6%E7%A7%8D%E6%96%B9%E6%B3%95/
利用CSS進行元素的水平居中,比較簡單,行級元素設置其父元素的text-align center,塊級元素設置其本身的left 和 right margins為auto即可。本文收集了六種利用css進行元素的垂直居中的方法,每一種適用於不同的情況,在實際的使用過程中選擇某一種方法即可。
Line-Height Method
試用:單行文本垂直居中,demo
代碼:
html
<div id="parent">
<div id="child">Text here</div>
</div>

css
#child {
line-height: 200px;
}
垂直居中一張圖片,代碼如下
html
<div id="parent">
<img src="image.png" alt="" />
</div>
css
#parent {
line-height: 200px;
}
#parent img {
vertical-align: middle;
}

CSS Table Method

適用:通用,demo
代碼:
html
<div id="parent">
<div id="child">Content here</div>
</div>

css
#parent {display: table;}
#child {
display: table-cell;
vertical-align: middle;
}

低版本 IE fix bug:
#child {
display: inline-block;
}

Absolute Positioning and Negative Margin

適用:塊級元素,demo
代碼:
html
<div id="parent">
<div id="child">Content here</div>
</div>
css
#parent {position: relative;}
#child {
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}

Absolute Positioning and Stretching

適用:通用,但在IE版本低於7時不能正常工作,demo
代碼:
html
<div id="parent">
<div id="child">Content here</div>
</div>

css
#parent {position: relative;}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}

Equal Top and Bottom Padding

適用:通用,demo
代碼:
html
<div id="parent">
<div id="child">Content here</div>
</div>
css
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}

Floater Div

適用:通用,demo
代碼:
html
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>
css
#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}

以上就是六種方法,可以在實際的使用過程中合理選擇,參考文章《
vertical-centering》。

熱門文章