Note: css margin collapsing

Source: Internet
Author: User

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
  • Stackoverflow
  • W3C

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.