What is a box model

When rendering a web page, all elements are described by the browser engine as a Box based on the CSS-box model. CSS determines the size, position, attributes (color, border…) of the Box. . The box model consists of content, padding, border and margin. The size of the box is determined by the content+padding+border, and the margin is the position the box occupies, not the size of the box.

Classification of box models

Box models fall into two categories: IE box models (or weird models) and standard box models. The difference between the two is:

  • Width /height = Content + border + padding
  • W3C standard box model: Width /height = content

1. Standard box model

As you can see, I set the width and height to 150, the inner margin to 10, the border to 5, and the bottom margin to 10, while the element actually appears to be 180. Width (150) + padding(2 * 10) + border(5 * 2) = 180

2. IE box model

As you can see from the figure, I set the width and height to 150, the inner margin to 10, the border to 5, and the bottom margin to 10, but the element is still presented as 150, and the content is changed to 120, but the size of the box is not changed.

Advantages and disadvantages of both box models

Take a chestnut

<style> .content-box { width: 150px; height: 150px; background: #fff; margin-bottom: 200px; } .child1 { float: left; width: 50%; height: 100px; padding: 10px; border: 5px solid red; background: #ccc; } .border-box { width: 150px; height: 150px; background: #fff; } .child2 { float: left; width: 50%; height: 100px; padding: 10px; box-sizing: border-box; border: 5px solid red; background: #ccc; } </style> <body> <div class="content-box"> <div class="child1"> </div> <div class="child1"> </div> </div> <div Class ="border-box"> <div class="child2"> Child 1</div> <div class="child2"> Child 1</div> </div>Copy the code

I’ve set both child elements to be 50% the width of the parent; When you want to add padding or border to child elements, the actual width of the standard model box will exceed 50%, resulting in line breaks. If you want the child element to be in the same line, you cannot set the width to 50%. Instead, you should calculate width:cacl(50%-2 * padding-2 * border); In the IE box model, the width of the content is adjusted according to the padding and border, and the true width of the element is always 50%, so there is no line feed.

Change box model

The current box model default in IE8 + and other browsers is Content-Box, the standard box model. You can switch with box-sizing.

box-sizing: content-box|border-box|inherit;

  • Content-box (Standard box model)
  • Border-box (IE box model)
  • Inherit (specify that the value of the box-sizing attribute should be inherited from the parent element)

conclusion

Box-sizing is a fun way to change your box models to suit your needs