A concept,

CSS box model is essentially a box that encapsulates the surrounding HTML elements, including margin, border, padding and content.

1.1 W3C Box Model (Standard Box Model)

content-boxContent box – Content is the boundary of the box

1.2 IE Box Model (Weird Box Model)

border-boxBorder box – The border is the border of the box

1.3 Calculation Formula

  • Content Box The width or height of the content box can be calculated as: width/height=content

  • Border-box The width or height of the border box is calculated as: width/height = Content + padding + border

  • Border-box is commonly used

Second,marginMerge and Blockmarginmerge

mergers

  • Father and sonmarginMerge (upper and lower margin merge, left and right not merge)
  • brothermarginmerge

How to Stop a merger

  • Combination of father and childpadding / border blocking
  • Combination of father and childoverflow: hiddenblocking

When overflow is not visible, that is, auto or Hidden, a BFC is created

BFC vertical margin overlap problem

<style>
        #margin {
            background: #1890FF;
            overflow: hidden;
        }
        #margin p {
            margin: 15px auto 25px;
            background: red;
        }
    </style>

    <section id="margin">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
    </section>
Copy the code

The top margins of 1, 2, 3 and 4 should all be 15px, and the bottom margins should all be 25px. Obviously, the margins between 1 and 2, 2 and 3,3 and 4 overlap. The rule of overlap is to take a larger value, that is, the distance between 1 and 2 is 25px.

Add a parent element to a child element and then add a BFC to the parent element to solve the margin overlap problem, as follows: Add a parent div to 2 and give the style Overflow: hidden.

 <style>
        #margin {
            background: #1890FF;
            overflow: hidden;
        }
        #margin p {
            margin: 15px auto 25px;
            background: yellowgreen;
        }
    </style>
    <section id="margin">
        <p>1</p>
        <div style="overflow: hidden">
            <p>2</p>
        </div>
        <p>3</p>
        <p>4</p>
    </section>
Copy the code

There is no margin overlap between 1 and 2,2 and 3, and the margins are now 15+25=40px instead of the larger 25px.