0

Any css masters know why this is happening? Or can explain it? The p is being hoisted to behave like it is inside the div by adding position relative to body. I know position:static happens to the body by default, but when I set it to relative, the p tag behaves like it is nested inside the div tag. Anyone knows why this behavior is happening?

body {
    background-color: purple;
    margin: 0px;
    padding: 0px;
    position: relative;


}

div {
    background-color: red;
    height: 100px;
    position: relative;
    margin:0px;
    padding: 0px;

}


p {
    background-color: blue;
    position: absolute;
    bottom: 0px;
    margin:0px;
}
<!DOCTYPE html>
<html>
  <body>
        <div>
        <!-- it behaves like if it was here -->
        </div>
        <p>Hello World</p>
  </body>
</html>
V.Villacis
  • 864
  • 1
  • 7
  • 19

1 Answers1

2

The p is positioned at the bottom of its containing block

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:

...

If there is no such ancestor, the containing block is the initial containing block.

and the "initial containing block" is

The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media.

So without position:relative on body, the element is placed at the bottom of the screen. with position:relative at the bottom of the body.

add border to the body element to see its boundary. The coloration is confusing you due to another feature which is background propagation

body {
  background-color: purple;
  margin: 0px;
  padding: 0px;
  position: relative;
  border:2px solid green;
}

div {
  background-color: red;
  height: 100px;
  position: relative;
  margin: 0px;
  padding: 0px;
}

p {
  background-color: blue;
  position: absolute;
  bottom: 0px;
  margin: 0px;
}
<!DOCTYPE html>
<html>

<body>
  <div>
    <!-- it behaves like if it was here -->
  </div>
  <p>Hello World</p>
</body>

</html>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • ok I did not know that. Correct once I remove the position: relative from the body, and move the P tag in between the div, the Hello World would stay in the same place as it is now. That is what was confusing me. – V.Villacis Feb 12 '22 at 20:11