【转】IE6、IE7下绝对定位position:absolute和margin的冲突bug解决方法

看到这篇帖子,我觉得真是豁然开朗,很好的文章就收藏了

 

先看一个代码:

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

这个代码在FF和IE8下都没有任何问题的,但是在IE6IE7下有人如下两个bug:

1,绝对定义(position:absolute)的相邻元素margin-top失效,但如果相邻元素(layer3)去掉width属性,margin-top又会生效。

2,layer1无法靠左,距离左边的距离为layer1的第一个非绝对定义元素(layer3)的margin-left值。

解决方法:

1,添加代码:,这也是网上找到的能够完全解决问题的方法。即代码变为:

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

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

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

3,这也是我这个文章所要说的最完美的解决方法,就是给绝对定义元素添加“float:left; display:inline;”定义。即代码变为:

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

文章来源:http://www.light-star.net/itemid3id155atpage.html







posted @ 2011-12-13 14:06  九叶  阅读(271)  评论(0编辑  收藏  举报