What is the CSS box model

MDN official website to explain:

The full CSS box model applies to block-level boxes, and inline boxes use only part of the content defined in the box model. The model defines each part of the box — margin, border, padding, content — that together create the content we see on the page.

For example:

Defining an element

<div class="box"></div>
Copy the code

Style this element as follows

.box {
    width: 100px;
    height: 100px;
    border: solid 1px #ddd;
    padding: 10px;
    margin: 10px;
}
Copy the code

Open the console and select the element as shown below

Two box models

  • —- Content is the boundary of the box —-W3C box model
  • Border-box —- Border-box is the border of the box —-IE box model (weird box model)

The difference between the two box models

Width and height are calculated differently

The content – the box:

width = content-width
height = content-height
Copy the code

Border – box:

width = content-width + padding + border
height = content-height + padding + border
Copy the code

Contrast figure