How will absolute positioning search for "relative" in nested div's?

Viewed 46

I'm trying to understand how nested divs works. I know that a "position absolute" search for a "position relative". But if we have a "position absolute" inside another "position absolute", what will it use as "position relative".

.box {
  border: 2px solid black;
  width: 500px;
  height: 500px;
  position: relative;
}

.box1 {
  position: absolute;
  width: 220px;
  height: 220px;
  border: 2px solid black;
  background-color: red;
  bottom: 25%;
  right: 25%;
}

.box2 {
  position: absolute;
  height: 70px;
  width: 70px;
  border: 2px solid black;
  background-color: green;
  left: 10%;
  bottom: 10%;
}
<div class="box">
  <div class="box1">
    <div class="box2"></div>
  </div>
</div>

It looks like in the result that box2 is absolute relative to box1. But shouldn't it be box, which is the first parent with "position relative"? Can anybody give an explanation of the mechanics?

1 Answers

I know that a "position absolute" search for a "position relative".

This is misconception.

An absolutely positioned element is positioned with respect to its closest positioned ancestor.

An element is positioned if it has any computed position property value that is not static.

This can be relative, absolute, fixed, or sticky.

position: relative is not a special case for this. It is just a positioning scheme that makes an element positioned without taking it out of normal flow. This makes it a popular choice for making an element the context for some absolute positioning without having side effects on the position of that element.

Related