0

HTML

<div class='parent'>
  <div class='child'>
    Hi
  </div>
</div>

CSS

.parent {
  background-color: #e5e5e5;
}

.child {
  background-color: #999999;
  margin: 20px;
}

When this renders, the top and bottom margin on the child div is missing. After applying the following styles to the .parent class, margins reappear. Why is this?

.parent {
  margin: -1px;
  padding: 1px;
}

https://jsfiddle.net/trxek0kc/2/

Krimson
  • 7,386
  • 11
  • 60
  • 97

3 Answers3

3

In some cases, top and bottom margins are collapsed. You can read more about it here. What's happening is this:

If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of its first child block, [...] then those margins collapse. The collapsed margin ends up outside the parent.

Jess Kenney
  • 389
  • 1
  • 3
0

Hey If I understand correctly, You have to add padding to parent element rather than giving margin to the child element. Then you will get your desired result.

.parent {
  background-color: #e5e5e5;
  padding: 20px;
}

.child {
  background-color: #999999;

}

or you can add add overflow property to parent element

.parent {
  background-color: #e5e5e5;
  overflow: hidden;
}
MontyGoldy
  • 739
  • 1
  • 13
  • 25
0

it's not missing but it's applied to the body,

see more details here : collapsing margins

In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored,

Taki
  • 17,320
  • 4
  • 26
  • 47