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>
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>