Margin top causes parent div to fall

Viewed 75

.d1 {
  background-color: lightblue;
}

.d2 {
  background-color: yellow;
  margin-top: 20px;
}
<div class="d1">
  <div class="d2">Test</div>
</div>

In this simple example, d1 is the parent element of d2. But d2 causes both itself and d1 to have a margin-top of 20px. Why does it behave this way?

1 Answers

Its simple logic that, when you are using parent div and child div, then parent div will be overwrite by child div style because parent will check all inside style and give you output.

Example: if you use margin-top: 20px; in both d1 & d2, it will give you output from top 40px.

Related