IE6和IE7下绝对定位position:absolute和margin的冲突问题解决

绝对定位的Position:absoulte的元素,会让相邻的兄弟元素的margin-top失效。而若是去掉了兄弟元素的高度又会正常。css

<div id="layer1" style="margin:20px; border:1px solid #F88; width:400px; ">
    <div id="layer2" style="position:absolute; background-color:#ccc;">Absolute (layer2)</div>
    <div id="layer3" style="margin:30px auto; width:200px; height:80px; background-color:#36F;">Normal Text Content
        (layer3)
    </div>

效果图:html

image

image

image
从运行的效果图能够看到在chrome下是没有问题的,在IE7下就出现了,我开头所说的问题,FF也是没有问题的!chrome

BUG主要有如下两个:一、Layer2在IE7下相邻的兄弟结点即Layer3的margin-top没有用了,二、layer2 没法靠左,距离左边的距离为layer1的第一个非绝对定义元素(layer3)的margin-left值。spa


解决的方案有如下几种:
一、添加代码:添加代码:<!–[if lte IE 7]>.net

<[endif]–>,这也是网上找到的可以彻底解决问题的方法。即代码变为:

<div style=”margin:20px; border:1px solid #F88; width:400px; “> <div style=”position:absolute; background-color:#ccc;”>Absolute (layer2)</div> <!–[if lte IE 7]><div></div><![endif]–> <div style=”margin:30px auto; width:200px; height:80px; background-color:#36F;”>Normal Text Content (layer3)</div> </div>

二、外围元素加position:relative定义,绝对定义元素加left和top定义。此方法能够解决第二个bug,没法解决第一个bug。也有说法用padding-top替代margin-top的,可是有时能够这样,有时候毕竟不行的。code

<div style=”margin:20px; border:1px solid #F88; width:400px; position:relative”> <div style=”position:absolute; background-color:#ccc; left:0; top:0;”>Absolute (layer2)</div> <div style=”margin:30px auto; width:200px; height:80px; background-color:#36F;”>Normal Text Content (layer3)</div> </div>

三、这是本文所要阐述的方法,相对来讲比较完美一些。给绝对定义元素添加“background-color:#CCC; float:left; display:inline;”定义,背景色千万不能够去掉,若是没有背景色就加一个透明(background-color:transparent;)。即代码变为:orm

<div style=”margin:20px; border:1px solid #F88; width:400px;”> <div style=”position:absolute; background-color:#ccc; float:left; display:inline;”>Absolute (layer2)</div> <div style=”margin:30px auto; width:200px; height:80px; background-color:#36F;”>Normal Text Content (layer3)</div> </div>

参考:htm

http://www.jb51.net/css/74238.htmlget

相关文章
相关标签/搜索