Home >Web Front-end >CSS Tutorial >Why Does My Fixed Header Appear to Have Extra Top Margin?
In your Codepen, you set the header to be fixed, which means that it will stay in the same position while scrolling down. However, when you did that, the margin on the top of the header seemed to increase. This is caused by margin collapsing.
Margin collapsing is a CSS behavior that collapses the margins of adjacent block-level elements, such as your header and the form below it. When the header becomes fixed, it is removed from the flow of the document and the form becomes the first in-flow element. This causes the top margin of the form to collapse with the top margin of the body, resulting in the appearance of a larger margin.
Two common ways to handle this issue are by disabling margin collapsing or setting a top margin value to the element that needs it.
To disable margin collapsing, add the padding-top: 1px CSS rule to the body element. This forces the browser to maintain the top margin of the body.
body { padding-top: 1px; /* Disable margin-collapsing */ }
Alternatively, add a top margin to the header. This will set the distance between the header and the top of the viewport:
#header { margin-top: 2rem; }
The above is the detailed content of Why Does My Fixed Header Appear to Have Extra Top Margin?. For more information, please follow other related articles on the PHP Chinese website!