0

I saw this problem accidently. But it looks so weird I try to understand what is going on here but I can't find any answer. Can anyone explain me this issue?

Look at this css. Header have margin-top but margin not applied to heder elemnt. My expactation was I saw little red space top of header. But this is not work.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  background-color: white;
}

body {
    background-color: red;
    margin: 20px;
}

header {
  height: 100vh;
  margin-top: 20px;
  background-color: blue;
}

https://jsbin.com/rexobepayo/edit?html,css,output

Murad Sofiyev
  • 790
  • 1
  • 8
  • 25
  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing – Mitya Jul 02 '20 at 18:32

2 Answers2

1

This is happening due to what's called margin collapsing. As MDN puts it:

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing.

So in other words, because the body and the header both have margin-top, the browser picks the largest (in your case they're the same) and applies one only.

Mitya
  • 33,629
  • 9
  • 60
  • 107
1

It's all working well. The effect you are getting now is because of collapsing margins. Your body has a margin of 20px and your header also has a margin of 20px. If we look into this situation, both margins are placed on top of each other and the larger margin will overlap the smaller one. If you remove the margin of the body, you will clearly see the top margin of the header. You can know more about collapsing margins on https://css-tricks.com/what-you-should-know-about-collapsing-margins/ .

Praneet Dixit
  • 1,393
  • 9
  • 25