The margin collapsing of the little kee CSS

Source: Internet
Author: User

Recently in the Web page design, the inexplicable discovery of the top will appear a horizontal bar, color is the background color of HTML. The original intention is that the empty horizontal bar should be the background color of the header. Check some information, found that is the problem of margin collapsing, record down, hope beginners less detours.

Starting with the question,

First give the demo source and screenshots, give an intuitive impression. The code is as follows:

<!        DOCTYPE html>

The screenshot is as follows (note the top blue horizontal bar, which is designed to be red):


The cause of the problem

Margin collapsing, border merge. H1 the default Margin-top value is greater than 0,H1, the top margin is merged with the top margin of the header, and the merged top margin is merged with the body's top margin, HTML is the root element and no longer merges. So the bar is the margin of the body and the color is the background of the HTML.

Solutions

There are two ways to solve the problem. One is to remove the margin, which is to set the margin to 0, and the other is to destroy the margin collapsing.

Margin set to 0

Really simple, the code is as follows:

h1{    margin-top:0px;}
Destroy margin collapsing

There are many methods here, as long as the rules for the margin collapsing, destroying one or more links.

To set the parent element's overflow to auto or hidden, the code is as follows:

#header {    width:100%;    height:38%;    margin:0px;    padding:0px;    background-color:red;    Overflow:auto;}

Set to non-negative padding, the code is as follows:

#header {    width:100%;    height:38%;    margin:0px;    padding:0px;    background-color:red;    padding-top:0.1px;}

To set the border, the code is as follows:

#header {    width:100%;    height:38%;    margin:0px;    padding:0px;    background-color:red;    border:1px solid Red;}
Reference links
    • 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.