【问题标题】:Why is an absolutely positioned element placed by its sibling instead of at the top corner of the page?为什么一个绝对定位的元素被它的兄弟元素而不是在页面的顶角放置?
【发布时间】:2015-06-21 08:43:00
【问题描述】:
我不明白为什么我的绝对定位元素出现在我的child_static div 之后。我一直认为绝对定位的元素会被排除在流程之外。那么为什么child_absolute 不覆盖child_static div?
.parent {
position: relative;
}
.child_static {
height: 20px;
background: blue;
}
.child_absolute {
position: absolute;
height: 20px;
width: 100%;
background: green;
}
<div class='parent'>
<div class='child_static'></div>
<div class='child_absolute'></div>
</div>
http://jsfiddle.net/4v4eLtp1/
【问题讨论】:
标签:
html
css
css-position
absolute
【解决方案1】:
我一直认为绝对定位的元素不合时宜。
是的,它们已从正常流程中移除。
我不明白为什么绝对定位元素出现在 child_static div 之后。
仅仅因为绝对定位会从正常流中移除元素,并不意味着它也会改变元素的位置。
换句话说,绝对定位的元素与它们没有绝对定位的位置相同除非它们的top、left、...设置了偏移量。
所以发生的情况是它们会重叠下一个兄弟元素,因为它们不再是文档流的一部分。
例如看看下面的例子,gold <div> 元素被absolutely 定位元素覆盖。
.parent {
position: relative;
}
.child_static {
height: 20px;
background: blue;
}
.child_absolute {
position: absolute;
height: 20px;
width: 100%;
background: green;
}
.child_static ~ .child_static {
background: gold;
}
<div class='parent'>
<div class='child_static'>Green</div>
<div class='child_absolute'>Blue</div>
<div class='child_static'>Gold</div>
</div>