4

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

misterManSam
  • 24,303
  • 11
  • 69
  • 89
darkchampionz
  • 1,174
  • 5
  • 24
  • 47
  • Your code working perfectly fine. try adding some content in d1 and you will see. right now you don't have anything so its not showing and d2 leaving margin-top. – Sumit Patel Oct 17 '19 at 04:37
  • This is the default behaviour. Similar questions asked here. https://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element – JustCode Oct 17 '19 at 04:56

1 Answers1

-2

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.