As I pondered the concept of stacking context, a question arose in my mind. Through my readings, I learned that by not applying any CSS properties that create a stacking context (such as position), it is possible to stack elements on top of each other using negative margins. For instance, you can have three divs where the third one sits atop the second and first, while the second one sits on top of the first. So far, so good.
My query is this: if we maintain the hierarchy of the three divs without altering it (with the third on top of the second and first, and the second on top of the first) using either negative margins or a CSS property like position, what differences might emerge? Could this impact responsiveness or any other aspect?
I've included some code for reference below so you can better grasp the scenario. Feel free to toggle between the different CSS code blocks within the comments line. The outcome remains the same!
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 1px solid black;
width: 400px;
height: 400px;
}
.container div {
border: 1px solid black;
width: 50px;
height: 50px;
}
/*Effect with POSITION*/
.container :nth-child(3) {
background-color: palegoldenrod;
position: relative;
bottom: 10px;
left: 10px;
}
/*Effect with negative MARGIN*/
/*.container :nth-child(3) {
background-color: palegoldenrod;
margin-top: -10px;
margin-left: 20px;
}*/
<div class='container'>
<div></div>
<div></div>
<div></div>
</div>
Thank you!