Recently, when designing web pages, you may find that a horizontal bar appears at the top of the page, and the color is the background color of html. The original intention is that the blank crossbar should be the background color of the header. I checked some information and found it was a margin collapsing problem. I recorded it and hoped that beginners would not take a detour.
Starting from the question
First, the demo source code and screenshots are provided to give an intuitive impression. The Code is as follows:
<!DOCTYPE html>
The screenshot is as follows (note that the blue horizontal bar above is designed to be red ):
Cause
Margin collapsing, border merging. By default, the margin-top value of h1 is greater than 0. The top margin of h1 is merged with the top margin of the header. The merged top margin is merged with the top margin of the body. html is the root element, the horizontal bar is the margin of the body, and the color is the background color of html.
Solution
There are two solutions. First, remove margin, that is, set margin to 0; second, destroy margin collapsing.
Set margin to 0.
The Code is as follows:
h1{ margin-top: 0px;}
Damage margin collapsing
There are many methods here, as long as they are rules for margin collapsing and destroy one or more of them.
Set the overflow of the parent element to auto or hidden. The Code is as follows:
#header { width: 100%; height: 38%; margin: 0px; padding: 0px; background-color: red; overflow: auto;}
The Code is as follows:
#header { width: 100%; height: 38%; margin: 0px; padding: 0px; background-color: red; padding-top: 0.1px;}
The code for setting border is as follows:
#header { width: 100%; height: 38%; margin: 0px; padding: 0px; background-color: red; border:1px solid red;}
Reference