为什么绝对定位元素由其兄弟元素放置而不是放置在页面的顶角? [英] Why is an absolutely positioned element placed by its sibling instead of at the top corner of the page?

查看:32
本文介绍了为什么绝对定位元素由其兄弟元素放置而不是放置在页面的顶角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我的绝对定位元素出现在我的 child_static div 之后.我一直认为绝对定位的元素是从流程中取出的.那么为什么 child_absolute 不覆盖 child_static div?

.parent {位置:相对;}.child_static {高度:20px;背景:蓝色;}.child_absolute {位置:绝对;高度:20px;宽度:100%;背景:绿色;}

<div class='child_static'></div><div class='child_absolute'></div>

http://jsfiddle.net/4v4eLtp1/

解决方案

我一直认为绝对定位元素是不合时宜的.

是的,它们已从正常流程中移除.

<块引用>

我不明白为什么绝对定位元素出现在 child_static div 之后.

仅仅因为绝对定位将元素从正常流中移除,并不意味着它也确实改变了元素的位置.

换句话说,绝对定位的元素将与它们不绝对定位的位置相同除非它们的top, left, ... 设置了偏移量.

所以发生的情况是它们会重叠下一个兄弟元素,因为它们不再是文档流的一部分.

例如看看下面的例子,其中 gold

元素被 absolutely 定位的元素覆盖.

.parent {位置:相对;}.child_static {高度:20px;背景:蓝色;}.child_absolute {位置:绝对;高度:20px;宽度:100%;背景:绿色;}.child_static ~ .child_static {背景:黄金;}

<div class='child_static'>Green</div><div class='child_absolute'>蓝色</div><div class='child_static'>Gold</div>

I don't understand why my absolutely positioned element appears after my child_static div. I always thought that absolutely positioned elements are taken out of the flow. So why doesn't child_absolute cover the 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/

解决方案

I always thought that absolute positioned elements are out of the flow.

Yes, they are removed from normal flow.

I don't understand why absolute positioned element appeared after child_static div.

Just because absolute positioning removes elements from normal flow, it doesn't mean it does alter the position of the elements as well.

In other words, absolutely positioned elements would be at the same place as they are not positioned absolutely unless their top, left, ... offsets are set.

So what happens is that they would overlap next sibling elements, because they are not part of document flow anymore.

For instance have a look at the following example where the gold <div> element is covered by absolutely positioned element.

.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>

这篇关于为什么绝对定位元素由其兄弟元素放置而不是放置在页面的顶角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆