CSS Box Sizing: Taming the Beast
The CSS Box Model is the foundation of web layout. However, its default behavior has frustrated developers for decades. Understanding and changing the `box-sizing` property is the first step to becoming a true UI master.
The Default: content-box
By default, the box-sizing property is set to content-box. This means that when you set a width or height on an element, you are only setting the size of the content area.
If you then add padding or a border, those values are added on top of your declared width and height. For example, a box with width: 200px, padding: 20px, and border: 5px solid will actually consume 250px of horizontal space (200 + 20 + 20 + 5 + 5). This makes creating precise grids incredibly frustrating!
The Hero: border-box
Enter box-sizing: border-box. When applied, this property tells the browser to include padding and borders inside the declared width and height.
Using the same example as before, if you declare width: 200px, the box will stay exactly 200px wide. The 20px padding and 5px border will shrink the available space for the inner content, rather than expanding the box outward.
The Universal Reset
Because border-box is so vastly superior for creating reliable layouts, it is considered a best practice to apply it to every single element on your website. We do this using the universal selector *.
*,
*::before,
*::after {
box-sizing: border-box;
}❓ Frequently Asked Questions
What's the difference between content-box and border-box?
content-box (Default): The `width` and `height` only apply to the content. Padding and border are added on top of that measurement, making the element larger.
border-box: Padding and border are included inside the specified `width` and `height`. The element's size stays strict and the internal content shrinks to accommodate padding/border.
Why does my layout break when I add padding?
This happens because you're using the `content-box` model (CSS's default). If you have two columns of 50% width and add padding to them, they'll take up more than 100% together and the second column will wrap to the next line. Applying `box-sizing: border-box` fixes this instantly.
Is margin (margin) included in border-box?
NO. No `box-sizing` model includes margins. Margins always create space outside the element, separating it from other elements, regardless of whether you use `content-box` or `border-box`.
