用CSS有多种方法实现垂直居中对齐。如果已知外部div的高度,不管是否知道内部div的高度,垂直居中实现起来很简单,但如果内部div高度是变量,如文字,垂直居中实现起来就比较复杂了,很可能需要使用hacks。如:
1、已知高度情况
很简单,直接计算就可以了
2、通过display: table属性布局
通过使用 display: table;
和vertical-align: middle
可以比较轻松的实现垂直居中,但IE6和IE7并不识别table和table-cell属性,必须使用hacks作为补充。
IE6和IE7的CSS
显示为
IE6和IE7的hack
补充: 如果想实现流式布局,加入如下CSS
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