Box Sizing in CSS
? CSS box-sizing Property
The box-sizing property controls how the width and height of an element are calculated — whether padding and borders are included inside the size or added outside it.
Values
| Value | Description |
|---|---|
content-box | Default behavior. width and height apply only to the content. Padding and border are added outside the size. |
border-box | width and height include content, padding, and border. The total size of the element stays fixed. |
inherit | Inherits the box-sizing value from its parent. |
Why it matters?
By default (content-box), the box model works like this:
div { width: 200px; padding: 20px; border: 5px solid black;}The content area is 200px wide.
Padding adds 40px total (20px left + 20px right).
Border adds 10px total (5px left + 5px right).
So, the actual element width = 200 + 40 + 10 = 250px.
With box-sizing: border-box:
div { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black;}The total width stays 200px.
The content width shrinks automatically to fit padding and border inside the 200px.
Common usage:
To make layouts easier and avoid unexpected sizing issues, many developers apply this globally:
/* Apply border-box sizing to all elements */*,*::before,*::after { box-sizing: border-box;}Summary
| box-sizing | width includes | Effect |
|---|---|---|
content-box | Content only | Padding & border increase total size |
border-box | Content + padding + border | Total size fixed, content shrinks if needed |
Need examples comparing the two or how to use box-sizing with flexbox/grid layouts?