0. Consider

<div class="box">
</div>
Copy the code
.box{
    width: 300px;
    height: 200px;
    padding: 10px;
    border: 1px solid #84a5e8;
    margin: 10px;
  }
Copy the code

I’ve created a rectangle. What is the width of this rectangle?

What is a box model?

CSS consists of boxes, roughly divided into block boxes and inline boxes. The block box has all the attributes of the box model, and the inline-block box has some attributes.

Block properties:

  • Have width, height (inline not available)
  • Inline inherits the width of the parent container, expands and takes up all the available space in the direction of the parent container (inline does not inherit, since width is not present)
  • Margin, border, and padding are used to push other elements away (inline applies to border, but does not push other elements away)
  • Line breaks (inline does not)

From these properties, the page we see is built. There are two box models in browsers today, the standard box model and the IE box model.

2. Attributes in the box model

Again a screenshot of the above elements in Chrome’s DevTools

  • Content box in the standard box model is where the content width and heiht are defined
  • Padding Box inner margin
  • The border box wraps the inner margin and content
  • Margin box Margin

2.1 Standard box model

In the standard model, if you set width and height for the box, you actually set the content box, so the initial answer to the question would be offsetWidth = 300 + 102 + 12 = 322

2.2 IE Box Model

In IE box model, setting width and heigth is to set the width and height of the box. To use IE box model, just set box-sing

.box2 {
    box-sizing: border-box;
}
Copy the code