为什么当我将 body 设置为 position: relative 时,我会出现意想不到的行为

Why when I set the body to position: relative, I get unexpected behavior

有css高手知道这是为什么吗?或者可以解释一下吗?通过添加相对于 body 的位置,p 被提升为在 div 内。我知道 position:static 默认情况下发生在 body 上,但是当我将它设置为 relative 时,p 标签的行为就像嵌套在 div 标签内一样。有人知道为什么会发生这种行为吗?

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>

p 位于其 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.

“初始包含块”是

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.

所以如果 body 上没有 position:relative,该元素将放置在屏幕底部。 position:relative 在正文底部。

向正文元素添加边框以查看其边界。由于另一个功能 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>