The CSS box model is a primary part of our knowledge about stylesheets. It tells us what gives our element’s height and widths.
By default, an item’s total width or height comes from by adding its content, padding, and border. But there is a twist if we set an explicit width/height.
For example, if we set a 200px width to our container element and specify a 10px solid border on both sides we get an element with 220px total width.
This behavior is the default in CSS and tells that when we set an element width, we set it for the element’s content area only. The padding and border will – if there is any – be added to this value. We can work in this way, but sometimes it is unpleasant.
The Box-Sizing Property
And this is the point where the box-sizing property is coming into the picture. Using box-sizing, we can set how the browser calculates the widths and heights of our elements.
It has two different values:
- content-box, which is also the default,
- border-box, which wraps the content, padding, and border together.
Note that a margin doesn’t include in either way into the dimension.
Box-Sizing: Content-Box;
The box-sizing property’s default value is the content-box. In this case, the width or height is determined only by the content area. The padding, border, margin are excluded.
/* The element width will be 300px + 10px + 10px + 20px + 20px = 360px. */ .element { width: 300px; border-left: 10px solid red; border-right: 10px solid red; padding: 20px; }
Box-Sizing: Border-Box;
As you see from the previous example, calculating our layout in this way is not the easiest. We always have to work with fix values which is redundant and isn’t flexible.
For this reason, we have the border-box value, which tells the vendor to calculate the item’s width combining the content, padding, and border width but doesn’t include the margin.
/* The element width will be 300px. */ .element { width: 300px; border-left: 10px solid red; border-right: 10px solid red; padding: 20px; }
Using border-box value now we can quickly generate various layouts in a lot of different ways without worrying the calculation. If you check your favorite CSS framework’s code, I’m sure you will see that the box-sizing is set to border-box.
How to Define Border-Box Globally, Inherit from the HTML element
If you want to set the box-sizing to border-box, the best way is to set it to all of the elements in low specificity. The following snippet will do the job:
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; }