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