Static positioned elements affect Absolute position of subsequent sibling elements

拜拜、爱过 提交于 2019-12-05 10:30:46
Renzo Calla

As this answer explains, if there is no (top, left, right, bottom) attributes the position: absolute element will be positioned by default as if it was part of the normal flow

, 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

When W3Schools (and the CSS spec) says that an element is "positioned relative to" something, it is never referring to the element's siblings. It's referring to the element's containing block.

The reason a non-positioned element (position: static) affects the layout of subsequent absolutely positioned elements with auto offsets is because absposed elements with auto offsets will assume their static position (see this answer as well as this one RenzoCC links to), and an element's static position, by nature, is influenced by the layout of surrounding elements, especially preceding siblings.

What absolutely positioning an element without changing any of its offsets does, is cause elements that follow it to be laid out as if that element itself were not there. This is what taking an element out of the flow means.

Static position doesn't affect the Absolute position when it comes to the ancestor position which "position: relative".

But the "position: absolute" has a power to position itself whenever you want inside of the (see the additional code I made) "position: relative;" while the "position: static" don't have the ability to used the Top, Right, Bottom and Left because is it a default position where it is only located at the left side.

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;
}
<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 -->
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!