Content-box vs Border-box in CSS: Key Differences and Usage
content-box means the width and height apply only to the content, excluding padding and border, while border-box includes padding and border within the set width and height. This affects how elements size and layout on the page.Quick Comparison
Here is a quick side-by-side comparison of content-box and border-box sizing models in CSS.
| Factor | content-box | border-box |
|---|---|---|
| Definition | Width/height apply only to content area | Width/height include content, padding, and border |
| Default in CSS | Yes (default box-sizing) | No (must be set explicitly) |
| Padding and border effect | Add to total element size | Included inside total size |
| Layout impact | Element size grows with padding/border | Element size stays fixed with padding/border |
| Use case | When precise content size is needed | When fixed total size is needed for layout |
| Calculation complexity | Requires manual size adjustments | Simplifies size calculations |
Key Differences
The content-box model is the default in CSS. It means the width and height you set apply only to the content inside the element. If you add padding or borders, they increase the total size of the element beyond the set width and height. This can cause layout shifts if you are not careful.
On the other hand, border-box changes this behavior so that the width and height include the content, padding, and border. This means the total size of the element stays exactly as you set it, making it easier to control layouts, especially when using padding and borders.
Choosing between them affects how you calculate sizes and design responsive layouts. border-box is often preferred for modern layouts because it simplifies sizing and avoids unexpected element growth.
Code Comparison
This example shows a box with content-box sizing. The width is 200px, but padding and border add extra size.
div {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid black;
background-color: lightblue;
}Border-box Equivalent
This example uses border-box so the total width stays 200px including padding and border.
div {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid black;
background-color: lightblue;
}When to Use Which
Choose content-box when you want the width and height to control only the content area, and you plan to manage padding and borders separately. This is useful for precise content sizing.
Choose border-box when you want the total element size to stay fixed regardless of padding or border. This is ideal for consistent layouts, grids, and responsive designs where element size must not change unexpectedly.
Key Takeaways
content-box sizes only content, padding and border add to total size.border-box includes padding and border inside the set width and height.border-box simplifies layout by keeping element size fixed.border-box for easier responsive and grid layouts.content-box when you need exact content dimensions.