一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

整理CSS实现垂直居中的5种方法优缺点

时间:2015-05-12 编辑:简简单单 来源:一聚教程网

方法一

这个方法把一些div的显示方式设置为表格,因此我们可以使用表格的vertical-alignproperty属性。







Contentgoeshere







#wrapper{display:table;}

#cell{display:table-cell;vertical-align:middle;}

优点:
content可以动态改变高度(不需在CSS中定义)。当wrapper里没有足够空间时,content不会被截断

缺点:
InternetExplorer(甚至IE8beta)中无效,许多嵌套标签(其实没那么糟糕,另一个专题)

方法二:

这个方法使用绝对定位的div,把它的top设置为50%,topmargin设置为负的content高度。这意味着对象必须在CSS中指定固定的高度。

因为有固定高度,或许你想给content指定overflow:auto,这样如果content太多的话,就会出现滚动条,以免content溢出。



Contentgoeshere


#content{

position:absolute;

top:50%;



margin-top:-120px;/*negativehalfoftheheight*/

}

优点:
适用于所有浏览器
不需要嵌套标签

缺点:
没有足够空间时,content会消失(类似div在body内,当用户缩小浏览器窗口,滚动条不出现的情况)

方法三

这种方法,在content元素外插入一个div。设置此divheight:50%;margin-bottom:-contentheight;。
content清除浮动,并显示在中间。





Contenthere



#floater{float:left;height:50%;margin-bottom:-120px;}

#content{clear:both;position:relative;}

优点:
适用于所有浏览器
没有足够空间时(例如:窗口缩小)content不会被截断,滚动条出现

缺点:
唯一我能想到的就是需要额外的空元素了(也没那么糟,又是另外一个话题)

方法四

这个方法使用了一个position:absolute,有固定宽度和高度的div。这个div被设置为top:0;bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为0,因此margin:auto;会使它居中。使用margin:auto;使块级元素垂直居中是很简单的。



Contenthere

#content{

position:absolute;

top:0;

bottom:0;

left:0;

right:0;

margin:auto;



width:70%;

}

优点:
简单

缺点:
IE(IE8beta)中无效
无足够空间时,content被截断,但是不会有滚动条出现

方法五

这个方法只能将单行文本置中。只需要简单地把line-height设置为那个对象的height值就可以使文本居中了。



Contenthere

#content{line-}

优点:
适用于所有浏览器
无足够空间时不会被截断

缺点:
只对文本有效(块级元素无效)
多行时,断词比较糟糕

这个方法在小元素上非常有用,例如使按钮文本或者单行文本居中。