CSS垂直居中对齐

用CSS有多种方法实现垂直居中对齐。如果已知外部div的高度,不管是否知道内部div的高度,垂直居中实现起来很简单,但如果内部div高度是变量,如文字,垂直居中实现起来就比较复杂了,很可能需要使用hacks。如:

<div id="containingBlock">
      <div><p>This sentence will change in each example</p> </div>
</div>

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

 

CSS垂直居中对齐,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。