转自:http://www.osxcn.com/css/vertical-centering.html
看了CSS实现完美垂直居中这篇文章,文中提到的第四种方法和Vertical Centering in CSS这篇文章提到的方法原理一致,这确实是完美解决垂直居中问题的一个方法。但是本文的作者还特别强调那是他个人原创,引用一下他的原文:
我研究 IE layout 模式多年,还是找出了一个可以在IE中绝对居中的方法。这个方法就是基于IE layout的BUG,也可以算以毒攻毒。至于原理,不要问我,这是独门秘学,何况三言两语也讲不清楚,只要好用就行。
既然研究IE的布局都研究了多年,那么我相信了他的实力。但是在二楼我又发现一个“拍砖贴”,点击到它提到的Vertical Centering in CSS文中,也找到了这样一句话“I have found it going home on Wilson street.”,说明老外认为这个是他的原创,而且他还特别申明了原创时的时间和地点,虽然我们无从考证他走在威尔逊大道上是否在想这个问题,但是按文章发布的时间来判断,老外的要早一些,那么这个就变得有趣了。
讨论完原创问题再来研究一下它的原理,按照老外的文章加上我的简单翻译来说明这个方法。
它是利用IE错误的解释了使用百分比计算定位高度的BUG来达到目的。
先定义一个高度400px的DIV,使用相对定位,它的CSS为:
height: 400px;
position: relative;
overflow: hidden;
background-color:#09C
在里面放一层DIV,使用绝对定位,让它离上面有50%的距离,它的CSS为:
position: absolute;
top: 50%;
那么我们再在里面嵌套一个DIV,它的CSS为:
position: relative;
top: -50%;
height:40px;
意思就是向上移动“它”一半的高度,但是IE就错误的解释了“它”的高度,计数的高度采用了它内部嵌套内容的高度,但是像这样正好是垂直居中。搞懂了相对定位和绝对定位的道理这个就不难理解了。
如果要使用在IE和Mozilla浏览器中都能完美居中有多种hack方法,作者使用了在需要IE解释的属性前加下划线方法。(display: table是为支持display: table属性的浏览器准备的,它可以得到和使用表格一模一样的效果,也就是vertical-align: middle属性起作用了)
<div style=“display: table; height: 400px; _position: relative; overflow: hidden; background-color:#09C“>
<div style=“ _position: absolute; _top: 50%; display: table-cell; vertical-align: middle;“>
<div style=“ _position: relative; _top: -50%“>
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
我们还可以使用更好的结构化语句来达到目的,道理是一样的。
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN“ “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd“>
<html xmlns=“http://www.w3.org/1999/xhtml“>
<head>
<style type=“text/css“>
#outer {height: 400px; overflow: hidden; position: relative; background-color:#09C}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; position: static;}
#inner {position: relative; top: -50%} /* for explorer only */
/* optional: #inner[id] {position: static;} */
</style>
<title>Vertical Centering in CSS</title>
</head>
<body>
<div id=“outer“>
<div id=“middle“>
<div id=“inner“>
any text
any height
any content, for example generated from DB
everything is vertically centered
</div>
</div>
</div>
</body>
</html>
ps:如果遇到图片和文字并排,可以试试给图片一个float:left; vertical-align: middle;属性。














目前还没有英雄在这里留过话
本文评论的RSS TrackBack 地址
咱来说两句:
你得先 登录 才能吼上两嗓子啊。