1,利用設定行高
(1)單行文本垂直居中,
<div id="parent">
<div id="child">Text here</div>
</div>
#child {
line-height: px;
}
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5CdodWalhWLl5Was9CX3AzLcFTMwIzLcNHZh9GbwV3LcRnblRnbvNWLwd3Lcd2bsJ2Lc12bj5ibnl2clR2blNnbhZnL3d3dvw1LcpDc0RHaiojIsJye.png)
demo
ps:對于子節點的DOM設定line-height,使line-height等于height高,這對于節點元素是單行文本的較有效。其中這個行高比字型大小大哦~
(2)居中圖檔
<div id="parent">
<img src="image.png" alt="" />
</div>
#parent {
line-height: px;
}
#parent img {
vertical-align: middle;
}
本方法中行高需要比圖檔高度設定的更高。再對圖檔設定vertical-align:middle;
2,利用CSS表格(不是html表格)
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {display: table;}
#child {
display: table-cell;
vertical-align: middle;
}
demo
将父節點設定為表格表示tabel-cell,之後可以在子節點上使用vertical-align:middle.則子塊div裡頭的元素會垂直居中
在低版本的IE浏覽器中,要添加:
#child {
display: inline-block;
}
3,對于塊級元素
demo
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {position: relative;}
#child {
position: absolute;
top: %;
left: %;
height: %;
width: %;
margin: -% -%;
}
與前兩種方法最大的不同,此方法針對塊級元素,而且對各個浏覽器的适配比較好。
4,streching
demo
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {position: relative;}
#child {
position: absolute;
top: ;
bottom: ;
left: ;
right: ;
width: %;
height: %;
margin: auto;
}
對于top,bottom,left,right四個邊設定為0,并且把margin:auto。
但是對IE7以下的不相容。和上一個方法一樣的是,如果子塊的内容太多太大,大過父元素的話,大的部分會被隐藏。
5,設定padding
demo
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
padding: % ;
}
#child {
padding: % ;
}
裡頭的數值是需要自己計算的。比如說,父元素是400Px 的高度,子元素是100px的高度,我們就需要150px對于上下的padding。
150 + 150 + 100 = 400
則設定時根據百分比計算即可。
其實這裡面的padding用margin也無所謂,根據項目需要。
6,FLoat
demo
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>
#parent {height: px;}
#floater {
float: left;
height: %;
width: %;
margin-bottom: -px;
}
#child {
clear: both;
height: px;
}
将一個空的div浮動在我們的子元素之上,并且設定它的高度寬度都是父元素的50%。就像是充滿了上半部分的父元素。
因為有浮動,是以在子元素上我們需要clear:both,清除浮動。
子元素的上部分邊現在應該是在float層的下部分邊。為了居中,
将子元素往上移動它的一半高度,就是例子中的100px/2=50px,是以margin-bottom: -50px;
這個方法适用于大部分浏覽器。在使用這個方法居中的時候,必須要知道子元素的高度。
7,有關于FLEX的種種。
其實在不定寬高的垂直居中中,
{left:%;
top:%;
-webkit-transform:translate(-%,-%);
position:absolute;}
比較常用,但如果涉及到FELX,
可以使用以下進行垂直居中。
#parent{
justify-content:center;
align-items:center;
display:-webit-flex;
}
但是以上對于flex的還是在IE7下不相容哇咔咔。
是以為了保險的話,用舊flex,
#flexbox{
display:-webkit-flex-box;
-webkit-flex-box:;
box-pack:center;
box-align:center;
}
http://vanseodesign.com/css/vertical-centering/
- 本文部分翻譯以上連結