静态定位的元素会影响后续同级元素的绝对位置 [英] Static positioned elements affect Absolute position of subsequent sibling elements

查看:117
本文介绍了静态定位的元素会影响后续同级元素的绝对位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道任何具有 position:absolute 的元素都将相对于具有诸如 absolute relative 之类的位置属性的最近祖先进行定位。在 ,这在您要保持位置的情况下很有用:像刀尖一样,绝对靠近其兄弟姐妹,并使用margin属性对其进行操作,例如:

  margin-top:-40px; 
margin-left:30px;



,但是如果您设置了任何值(上,左,右,下),这将重置默认位置并相对于父级。

  top:0 


I understand that any element with position: absolute will be positioned relative to the nearest ancestor with a positional attribute such as absolute or relative. This is mentioned in various answers for example here. Also on the w3schools site here...

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However, inserting a static element appears to disrupt this rule and shifts the absolute element. I'd like to understand why that happens. See code snippet below.

If the static element is chaged to absolute, the subsequent elements are displayed as expected (according to the nearesst positional ancestor rule).

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>

解决方案

As , this is helpful in case you want to maintain a position: absolute next to its sibling like a tool tip would, and manipulate it with margin property, let say:

margin-top:-40px;
margin-left:30px;

but if you set any (top,left,right, bottom), this will reset the default position and will be relative to the parent.

top:0

这篇关于静态定位的元素会影响后续同级元素的绝对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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