.parent {
background-color: red;
width: 100px;
/* border: solid 5px black; */
}
.child {
margin-top: 50px;
width: 100px;
height: 100px;
background-color: green;
}
<html>
<head></head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
.parent {
background-color: red;
width: 100px;
border: solid 5px black;
}
.child {
margin-top: 50px;
width: 100px;
height: 100px;
background-color: green;
}
<html>
<head></head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
The only one single thing that changes in the code in the first and second examples are the border that is applied to the parent div. How come it only contains the margin of the child when the border is applied?
Apparently, this behavior has a name and is called "margin collapsing".
According to this MDN article:
One simple solution would be to change the display of the parent div to flex with column direction, like so: