Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ie6/7定位元素导致相邻元素的margin-top失效 #6

Open
matthew-sun opened this issue Jan 2, 2015 · 0 comments
Open

ie6/7定位元素导致相邻元素的margin-top失效 #6

matthew-sun opened this issue Jan 2, 2015 · 0 comments

Comments

@matthew-sun
Copy link
Owner

问题描述:

对于一个触发了haslayout的块级元素,且它的相邻元素是具有定位属性的,那么这个元素在IE6/7下的margin-top会失效。

html代码:
<div class="pos">定位元素</div>
<div class="bug">margin-top失效元素</div>
css代码:
.pos { position: fixed; left: 0; top: 0; width: 100%; background: blue; height: 40px; line-height: 40px; }
.bug { margin-top: 40px; background: red; height: 40px; line-height: 40px;  }

标准浏览器下输出的结果(正常):


normal

IE6/7下输出的产物(bug元素被遮住):


bug

具体可查看 Demo

WTF!

分析原因:

一个块级元素,触发了hasLayout(比如设置了宽度高度),并且其前面紧挨着的同级的节点如果为absolute绝对定位或者是固定定位,就会导致这个块级元素在IE6/IE7下面的margin-top失效,看起来就像margin-top:0一样。

关键词:自身触发haslayout,同级相邻节点定位

解决方案:

1.不使用margin属性:使用padding来代替margin,比如设置其父元素的padding-top,或者设置这个块元素的padding-top,不过要注意padding对其背景的影响。

.bug { padding-top: 40px; background: red; height: 40px; line-height: 40px;  }

2.避免两个元素相邻:在它们之间插入一个空div标签,或者交换这两个标签的前后位置。

<div class="pos">定位元素</div>
<div></div>
<div class="bug">margin-top失效元素</div>
或者(交换位置):
<div class="bug">margin-top失效元素</div>
<div class="pos">定位元素</div>

3.去掉失效元素的haslayout属性(特殊场景可使用,一般不推荐)

.bug { margin-top: 40px; background: red; line-height: 40px; }
希望这篇文章能对你有用,和我一起交流~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant