Problem 1: Child element margin affects parent element (margin collapse)

<style> *{ padding:0; margin:0; } body{ background:pink; } .container{ background:blue; margin:0 auto; }. Block -1{background:red; margin-top:20px; } </style> <body> <div class='container'>
        <div class='block-1'>1111</div>
    </div>
</body>
Copy the code

Contents specified in CSS2.1 box model:

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. All adjacent margins of two or more box elements will be merged into a shared margin. Adjacent is defined as sibling or nested box elements with no non-empty content, Padding, or Border separation between them.

So how do you solve this problem?

Margin collapse solution

1. Set a border or inner margin for the parent

.container{ background:blue; margin:0 auto; border-top:1px solid; // Padding-top :1px; // Second way}Copy the code

2. Trigger BFC (block-level format context) to change the parent rendering rules

Methods:

There are four ways to change the rendering rules of the parent, adding to the parent box

(1)position:absolute/fixed

(2)display:inline-block;

(3)float:left/right

(4) Overflow :hidden: visible(overflow:scroll, overflow:hidden, overflow:auto)

.container{
   float:left; / / orfloatExcept, except, exceptfloat: None produces BFC}Copy the code





.block-1{
    float:right; / / orfloat: left; In addition to notfloat: None produces BFC}Copy the code

Question 2: Margin merge (the vertical margin of two sibling elements is merged)

Margin merges occur only on block-level elements; Floating elements do not create margin merges with neighboring elements; Absolutely positioned elements do not create margin merges with adjacent elements; There is no margin merge between inline block level elements. No margin merges occur between root elements (such as between HTML and body);

p{
    margin:20px;
    background:red;
}
<body>
  <p>1111</p>
  <p>222</p>
</body>
Copy the code

How to solve it?

Add display:inline-block to the last element; For IE6 and IE7, however, use *display:inline; Zoom: 1; Float the last element (left/right)

// Child p:last-child{display:inline-block;float:left; // Both can be}Copy the code