Home > Web Front-end > CSS Tutorial > Why Does My Fixed Header Appear to Have Extra Top Margin?

Why Does My Fixed Header Appear to Have Extra Top Margin?

Mary-Kate Olsen
Release: 2024-12-19 05:29:14
Original
754 people have browsed it

Why Does My Fixed Header Appear to Have Extra Top Margin?

Why does my header moves down when I set it fixed?

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.

What is 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.

How to Fix

Two common ways to handle this issue are by disabling margin collapsing or setting a top margin value to the element that needs it.

Disabling Margin Collapsing

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 */
}
Copy after login

Setting a Top Margin Value

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template