用CSS有多种方法实现垂直居中对齐。如果已知外部div的高度,不管是否知道内部div的高度,垂直居中实现起来很简单,但如果内部div高度是变量,如文字,垂直居中实现起来就比较复杂了,很可能需要使用hacks。如:
This sentence will change in each example
1、已知高度情况
很简单,直接计算就可以了
#containingBlock {display: block; height: 200px;}
#containingBlock div {height:50px; margin: 75px 0;}
2、通过display: table属性布局
通过使用 display: table;
和vertical-align: middle
可以比较轻松的实现垂直居中,但IE6和IE7并不识别table和table-cell属性,必须使用hacks作为补充。
#containingBlock {display: table; height: 200px; position: relative; overflow: hidden;}
#containingBlock div {display: table-cell; vertical-align: middle;}
IE6和IE7的CSS
#containingBlock {height: 200px; position: relative; overflow: hidden;}
#containingBlock div { position: absolute; top: 50%;}
#containingBlock div p {position: relative; top: -50%;}
显示为
IE6和IE7的hack
//Vertical Alignment Table Display Hack
#containingBlock {display:table; height: 200px; position: relative; overflow: hidden; }
#containingBlock div {*position: absolute; top: 50%; display: table-cell; vertical-align: middle;}
#containingBlock p {*position: relative; top: -50%;}
补充: 如果想实现流式布局,加入如下CSS
html, body, #containingBlock {height: 100%; position:relative; }
#containingBlock div {height: 50%; position: absolute; top: 25%; }
3. 垂直居中所用到的参数
值 |
描述 |
length |
Raises or lower an element by the specified length. Negative values are allowed |
% |
Raises or lower an element in a percent of the “line-height” property. Negative values are allowed |
baseline |
Align the baseline of the element with the baseline of the parent element. This is default |
sub |
Aligns the element as it was subscript |
super |
Aligns the element as it was superscript |
top |
The top of the element is aligned with the top of the tallest element on the line |
text-top |
The top of the element is aligned with the top of the parent element’s font |
middle |
The element is placed in the middle of the parent element |
bottom |
The bottom of the element is aligned with the lowest element on the line |
text-bottom |
The bottom of the element is aligned with the bottom of the parent element’s font |
inherit |
Specifies that the value of the vertical-align property should be inherited from the parent element |
参考:
Vertical Centering With CSS
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net