I'm trying to study and understand the positions absolute
and relative
.
Scenario 1 (relative):
* {
padding: 0;
margin: 0;
}
#container {
width: 100%;
background-color: black;
}
#box1 {
width: 50%;
position: relative;
left: 20px;
color: white;
background-color: blue;
}
<div id="container">
<div id="box1">
<h1>This is box 1</h1>
</div>
</div>
I can completely understand the above. When given a relative positioning, its moving 20px from the left of its normal position. So what I studied in theory did make sense and this is clear.
Now, when I tried this - Scenario 2 (absolute):
* {
padding: 0;
margin: 0;
}
#container {
width: 100%;
background-color: black;
}
#box1 {
width: 50%;
position: absolute;
left: 20px;
color: white;
background-color: blue;
}
<div id="container">
<div id="box1">
<h1>This is box 1</h1>
</div>
</div>
Question: Why is that the black background is gone? From what I understood, box1
should move 20px to its left from its parent (which is currently the browser as I've used absolute for its position).
So it does move, but why is the black background (which was set in its parent) missing? Issn't Box1 nested into it? Why does it go missing?
I've tried googling but I'm unable to understand this logic and would love if someone could point me in the right direction.
Make absolute positioned div expand parent div height
I tried to look at this, however, once again I'm not understanding the correct answer.