我理解 position:absolute 的任何元素都将相对于最近的祖先定位,其位置属性如绝对或 relative 。这在例如here的各种答案中提到。也在w3schools网站here ...
位置为绝对的元素;是相对于 最近的祖先(而不是相对于 视口,像固定一样)。
但是,插入静态元素似乎会破坏此规则并移动绝对元素。我想知道为什么会这样。请参阅下面的代码段。
如果静态元素被追加到绝对值,则后续元素将按预期显示(根据最近的位置祖先规则)。
div.relative {
position: relative;
width: 440px;
height: 600px;
border: 3px solid #73AD21;
}
div.static {
position: static;
width: 200px;
height: 100px;
border: 3px solid #73ADff;
}
div.absolute {
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
div.absolute2 {
left:210px;
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #ffAD21;
}
<div class="relative">This div element has position: relative;
<div class="static">This div element has position: static</div>
<div class="absolute">This div element has position: absolute, but is positioned relative to the preceding static element, not the first positional ancestor.;</div>
<div class="absolute2">This div element also has position: absolute;</div>
</div>
答案 0 :(得分:3)
正如this回答所解释的那样,如果没有(top,left,right,bottom)属性,则position:absolute元素将默认定位,就像它是正常流的一部分一样,这有助于你想要保持一个位置:绝对在它的兄弟旁边就像工具提示一样,并用margin属性操纵它,让我们说:
margin-top:-40px;
margin-left:30px;
但是如果您设置任何(顶部,左侧,右侧,底部),这将重置默认位置并将相对于父级。
top:0
答案 1 :(得分:1)
当W3Schools(以及CSS规范)说某个元素是“相对于”某个东西时,它永远不会引用该元素的兄弟姐妹。它指的是元素的包含块。
非定位元素(position: static
)影响具有自动偏移的后续绝对定位元素的布局的原因是因为具有自动偏移的偏置元素将假定其静态位置(请参阅{ {3}}以及this answer RenzoCC链接到),并且元素的静态位置本质上受周围元素布局的影响,特别是在兄弟姐妹之前。
在不改变任何偏移的情况下绝对定位元素的原因是, it 之后的元素是如何布局的,就好像该元素本身不存在一样。这就是从流动手段中取出一个元素的原因。
答案 2 :(得分:0)
当它位于祖先位置时,静态位置不会影响绝对位置,其位置为:relative&#34;。
但是&#34;位置:绝对&#34;有权在内部定位自己(参见我制作的附加代码)&#34; position:relative;&#34;而&#34;位置:静态&#34;没有能力使用Top,Right,Bottom和Left,因为它是一个默认位置,它只位于左侧。
div.relative {
position: relative;
width: 440px;
height: 600px;
border: 3px solid #73AD21;
}
div.static {
position: static;
width: 200px;
height: 100px;
border: 3px solid #73ADff;
}
div.absolute {
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
/* Absolute Location inside the Relative Position */
top: 0;
left: 0;
}
div.absolute2 {
left:210px;
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #ffAD21;
/* Absolute Location inside the Relative Position */
top: 0;
}
&#13;
<div class="relative">This div element has position: relative;
<div class="static">This div element has position: static</div>
<div class="absolute">This div element has position: absolute, but is positioned relative to the preceding static element, not the first positional ancestor.;</div>
<div class="absolute2">This div element also has position: absolute;</div>
</div> <!-- / .relative -->
&#13;