日期:2013-10-12  浏览次数:21242 次

 什么叫绝对居中?就是说容器到屏幕左右上下四个方向都有间距,并且随屏幕大小缩放绝对不变或者等比例调整,一直居屏幕两头。

绝对居中也有两种情况,容器的绝对大小绝对大小

同时有很多方法可以实现,总结起来大致如下:

1,利用table特性,在width and height all set 100%的时候,可以把容器嵌套在td内构成绝对居中,此时的被嵌套容器可为绝对或者绝对大小。(非标准)
<table width="100%" height="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
  <td style="text-align:center;">
    <table width="200" height="50" border="0" cellpadding="0" cellspacing="0" bgcolor="#ef1122">
      <tr>
        <td> </td>
      </tr>
    </table>
  </td>
</tr>
</table>

效果演示:http://www.rexsong.com/blog/attachments/200512/14_094637_vertical_1.htm

2,利用负边距方法,绝对定位使容器绝对屏幕绝对居中,此时的被嵌套容器只能为绝对大小。(标准)

依据margin负值和top left的比例控制,实现随屏幕绝对居中,容器大小改变需求重新调整margin top left的参数:
<div style="background:#f00; width:740px; height:340px; left:50%; margin:-170px 0 0 -370px; position:absolute; top:50%;"></div>

效果演示:http://www.rexsong.com/blog/attachments/200512/14_095218_vertical_2.htm

3,老外给出的另类方法,巧妙利用display:inline-block;,IE6.0测试通过。(标准)

留意height:100%是关键:
body { margin:0; height:100%;}
#edge { width:0; height:100%; display:inline-block; vertical-align:middle;}
#container { text-align:center; width:100%; display:inline-block; vertical-align:middle;}

留意edge与container没有嵌套关系:
<!-- required for xhtml1.1 validation only -->
<span id="edge"></span>
<span id="container">
  <div style="width:200px; height:50px; background:#f00; line-height:50px;">仅IE6.0环境下实现</div>
</span>

这应该算是IE的一个bug,团体对display:inline-block理解无限。edge可以看作一个填充,container如今是一个上下居中的对象,加了背景色能看的更清楚,当然你也可以在container内添加任何绝对或者绝对大小容器。但问题在于span只是一个内联元素,在内部添加块级元素是不标准的逻辑。

效果演示:http://www.rexsong.com/blog/attachments/200512/14_095602_vertical_3.htm

4,CSS行为expression控制实现,不过expression为IE独有,并且耗资源严重,尤其在大量使用的时候。(标准)

留意关键定义,不要以为height:100%在IE内是没用的:
html,body { height:100%;}

实时获取屏幕高宽值,分别减去容器高宽值再除以2,得到精确坐标绝对定位:
<div style="background:#f00; position:absolute; left:expression((body.clientWidth-50)/2); top:expression((body.clientHeight-50)/2);width:50px;;height:50px;"></div>

效果演示:http://www.rexsong.com/blog/attachments/200512/14_100246_vertical_4.htm

5,DOM实现。(不在此讨论)

05.12.10

6,FF1.5测试通过,绝对定位,边距为比例,此时容器高宽一直为viewport的50%绝对大小(标准):
<div style="position:absolute; top:0; right:0; bottom:0; left:0; width:50%; height:50%; margin:auto; background:#f00; color:white; line-height:20px; text-align:center;">