网页制作 
首页 > 网页制作 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

首先我们来看一个代码:

复制代码代码如下:
<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> </div>

这个代码的效果如下:
IE6/IE7下绝对定位position:absolute和margin的冲突问题解决

在FF和IE8下都没有任何问题的,但是在IE6和IE7下有人如下两个bug:

a, 绝对定义(position:absolute)的相邻元素margin-top失效,但如果相邻元素(layer3)去掉width属性,margin-top又会生效。 b, layer1无法靠左,距离左边的距离为layer1的第一个非绝对定义元素(layer3)的margin-left值。 解决方法:

1,添加代码:<!–[if lte IE 7]><div></div><![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>

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

复制代码代码如下:
<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>

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

复制代码代码如下:
<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>

纠结了两天,时刻都在思考这个问题的解决思路,总算解决了。感谢桃子。

上一篇:css的边偏移距离针对left和right可能性值探讨
下一篇:背景半透明效果CSS链接样式代码
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网