日期:2014-05-17  浏览次数:20772 次

让绝对定位原素快速居中
根据绝对定位特点,假设某原素已设定位属性为绝对定位:position:absolute;那么该元素就会脱离正常文档流,此时设了绝对定位的元素的left,top,bottom,right的值如不设,默认并不是为0,该元素还会停留在原来的位置,只是不在正常文档流之中!同时该元素仍可以使用margin进行边距的偏移,而偏移的参照物就是其本身!因为绝对定位使用方向偏移再混合margin的方向偏移,两都同方向的值会累加!如left:20px;margin-left:20px;此时实际偏移的值是40px;根据这个规律,假如想让这个具有绝对定位的元素居中就有办法了!可以设:left:0px; right:0px; top:0px;而再设置margin:0px auto;即可使该元素靠上居中显示!这点在做顶部时也很方便哦!

------解决方案--------------------
光看这个方法,起初表示怀疑,虽说absolute之后,margin有效,但是用0 auto来居中怎么会有效果?
top left right bottom同时出现有疑问,因为之前也遇到过类似问题,同时出现的话,只有left,top有效,换句话説left top 比 right bottom的优先级高。

测试了下,在ff下居然真的句中了,但是ie6下却无动于衷。

HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
        <style>
            span {
                width:100px; height:100px;
                border:1px solid red;
                position:absolute; left:0; top:0; right:0; bottom:0;
                margin:0 auto;
            }
        </style>
    </head>
    <body>
        <span>123</span>
    </body>
</html>

------解决方案--------------------
<div style="position:fixed;width:100%;height:80px;left:0;bottom:0">
<div style="position:relative;width:960px;margin:0 auto;height:80px;background:#ccc;display:block;">
&nbsp;
</div>
</div>
------解决方案--------------------
span {
width:100px; height:100px;
border:1px solid red;
position:absolute; left:50%;
margin-left:-50px;/*50%宽度*/
}
------解决方案--------------------
span {
width:100px; height:100px;
border:1px solid red;
position:absolute; 
left:50%;top:50%;
margin: -50px -50px;
}