-1

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

body {
  height: 100vh;
}

header {
  background-color: gray;
  height: 200px;
}

body > header > h1 {
  margin-top: 5rem;
}
<body>
  <header>
    <h1>
      EXAMPLE
    </h1>
  </header>
</body>

In this code, when I gave margin-top to the h1 element, I thought that only the h1 element should be affected, but the margin affected not only the h1 but also the body element and shifted it down. What is the reason of this?

There is no problem when i use flex on body.

body {
  display: flex;
  flex-direction: column;
}
Gerard
  • 15,418
  • 5
  • 30
  • 52
Torvia
  • 7
  • 3

1 Answers1

-1

The reason the margin applied to the h1 element affects the body element as well is due to the default collapsing margins behavior in CSS. When two vertical margins of adjacent elements collapse, the resulting margin is the maximum of the two margins.

In your case, when you apply a margin to the h1 element, the margin collapses with the default margin of the body element, resulting in the larger margin being applied to the body element as well.

To prevent this collapsing margin behavior and ensure that the margin applied to the h1 element only affects itself, you can use one of the following approaches:

  1. Use overflow: hidden on the body element:

    body {
      overflow: hidden;
    }
    

    By applying overflow: hidden, you establish a new block formatting context for the body element, which prevents the collapsing margin from affecting the surrounding elements.

  2. Use padding instead of margin on the body element:

    body {
      padding-top: 20px; /* Or any desired value */
    }
    

    By using padding on the body element instead of margin, the spacing will be applied within the element itself, and there will be no collapsing margin issue.

  3. Use a wrapper div around the content within the body element:

    <body>
      <div class="wrapper">
        <!-- Content here -->
      </div>
    </body>
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    .wrapper {
      margin-top: 20px; /* Or any desired value */
    }
    

    By introducing a wrapper div, you contain the content within a separate element, preventing the margin collapse between the h1 and body elements.