方法三
这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;。 content 清除浮动,并显示在中间。
<div id="floater"> <div id="content"> Content here</div> </div>
#floater {float:left; height:50%; margin-bottom:-120px;} #content {clear:both; height:240px; position:relative;}
优点:
适用于所有浏览器 没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现
缺点:
唯一我能想到的就是需要额外的空元素了(也没那么糟,又是另外一个话题)
方法四
这个方法使用了一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。
<div id="content"> Content here</div>
#content { position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; height:240px; width:70%; }
优点:简单
缺点:
IE(IE8 beta)中无效 无足够空间时,content 被截断,但是不会有滚动条出现
方法五
这个方法只能将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。
<div id="content"> Content here</div>
#content {height:100px; line-height:100px;}
优点:
适用于所有浏览器 无足够空间时不会被截断
缺点:
只对文本有效(块级元素无效) 多行时,断词比较糟糕
这个方法在小元素上非常有用,例如使按钮文本或者单行文本居中。
出处:前端观察
责任编辑:bluehearts
上一页 CSS实现垂直居中的5种方法 [1] 下一页 CSS实现垂直居中的5种方法 [3]
◎进入论坛网页制作、WEB标准化版块参加讨论,我还想发表评论。
|