CSS垂直居中对齐

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

CSS垂直居中对齐
<div id="containingBlock">
      <div><p>This sentence will change in each example</p> </div>
</div>
CSS垂直居中对齐

1、已知高度情况

很简单,直接计算就可以了

CSS垂直居中对齐
#containingBlock {display: block; height: 200px;}
#containingBlock div {height:50px; margin: 75px 0;}
CSS垂直居中对齐

CSS垂直居中对齐

2、通过display: table属性布局

通过使用 display: table;vertical-align: middle可以比较轻松的实现垂直居中,但IE6和IE7并不识别table和table-cell属性,必须使用hacks作为补充。

CSS垂直居中对齐
#containingBlock {display: table; height: 200px; position: relative; overflow: hidden;}
#containingBlock div {display: table-cell; vertical-align: middle;}
CSS垂直居中对齐

CSS垂直居中对齐

IE6和IE7的CSS

CSS垂直居中对齐
#containingBlock {height: 200px; position: relative; overflow: hidden;}
#containingBlock div { position: absolute; top: 50%;}
#containingBlock div p {position: relative; top: -50%;}
CSS垂直居中对齐

显示为

CSS垂直居中对齐

IE6和IE7的hack

CSS垂直居中对齐
//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垂直居中对齐

CSS垂直居中对齐

补充: 如果想实现流式布局,加入如下CSS

CSS垂直居中对齐
html, body, #containingBlock {height: 100%; position:relative; }
#containingBlock div {height: 50%; position: absolute; top: 25%; }
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

 

CSS垂直居中对齐,布布扣,bubuko.com

CSS垂直居中对齐

上一篇:php递归数组中的应用


下一篇:Apache2.4.6服务器安装及配置