div上的CSS位置如何影响兄弟分区的位置? [英] How does the CSS position on a div affects position of sibling division?
问题描述
我一直在在Alistapart上发布CSS文章。下面的代码片段引起了我的注意,并且无法理解背后的理论。
在html / css下方显示两个框。但是,如果我将#box_1的位置更改为绝对位置,则#box_2会重叠#box_1。
<!DOCTYPE html>
< html lang =en>
< head>
< style>
#box_1 {
position:relative;
width:200px;
height:200px;
背景:#ee3e64;
}
#box_2 {
position:absolute;
width:200px;
height:200px;
背景:#44accf;
}
< / style>
< / head>
< body>
< div id =box_1>< / div>
< div id =box_2>< / div>
< / body>
< / html>
-
另一个box(box_1)的位置会如何影响不同/同级格的位置(box_2)。在上面的css(box_1中的position:relative;)中,绝对应该总是绝对地只对非直接的非静态父对象有效吗?
,如果我添加top:0到#box_2,box_2看起来又重叠了。为什么会发生这种情况? 它的静态位置,如果你没有指定 How does the position of another box (box_1) affects position of a different/sibling div(box_2). Isn't 'absolute' should always absolute only to immediate non-static parent?
In the above css (with "position: relative;" in box_1), if I add "top: 0;" to #box_2, then box_2 appears to overlap again. Why does this happens?
顶部
,右
的任何, bottom
或 left
属性,而不管其祖先是否被定位。这就是为什么当你简单地将它设置为 position:absolute
时,#box_2
没有任何变化 - 相反,它受到#box_1
就像您未指定 position:absolute
。 但是,请注意,#box_1
仅影响#box_2
,因为1先于2;一旦你绝对地定位#box_2
,它将被从流中取出,并且其后的任何兄弟将像#box_2
不再存在。查看这个例子,我在这里创建一个#box_3
这就是与#box_1
相同,并在 #box_3
overlapps #box_2
因为3在正常流程中看不到2;它只看到1。
一旦您设置 I have been going through CSS Positions articles on Alistapart. Below snippet caught my attention and couldn't fathom the theory behind. Below html/css shows two boxes one over other. But if I change the position of #box_1 to absolute, then #box_2 overlap #box_1.
An absolutely-positioned element will remain in its static position if you don't specify any of its However, note that Once you set 这篇关于div上的CSS位置如何影响兄弟分区的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! top:0
到#box_2 code>,那么它知道它必须被附加到视口的顶部(因为它的祖先没有被定位,所以它的包含块)。
<!DOCTYPE html >
<html lang="en">
<head>
<style>
#box_1 {
position: relative;
width: 200px;
height: 200px;
background: #ee3e64;
}
#box_2 {
position: absolute;
width: 200px;
height: 200px;
background: #44accf;
}
</style>
</head>
<body>
<div id="box_1"></div>
<div id="box_2"></div>
</body>
</html>
top
, right
, bottom
or left
properties, regardless of whether any of its ancestors is positioned. That's why nothing appears to happen to #box_2
when you simply set it to position: absolute
— instead, it's affected by #box_1
in the same way as if you hadn't specified position: absolute
.#box_1
affects #box_2
only because 1 precedes 2; once you absolutely position #box_2
it is taken out of the flow and any siblings that follow it will flow as if #box_2
was no longer there. See this example where I create a #box_3
that's identical to #box_1
and add it after #box_2
, in which #box_3
overlaps #box_2
because 3 doesn't see 2 in the normal flow; it only sees 1.top: 0
to #box_2
, then it knows it has to be attached to the top of the viewport (as its containing block since none of its ancestors are positioned).