June 23, 2025
O. Wolfson
Every element on a web page is essentially a rectangular box. Understanding how these boxes behave and interact with each other is fundamental to mastering layout in CSS. This is where the CSS Box Model comes in.
Total Rendered Size: 200px
box-sizing: border-box
Margin: 20px
Border: 10px
Padding: 20px
Content Size: 100px
The CSS Box Model describes how the size of an element is calculated based on four areas:
[ Margin ]
[ Border ]
[ Padding ]
[ Content ]
Imagine a set of nested boxes, each wrapping the next. When you set dimensions like width and height in CSS, itβs crucial to know which part of the box youβre affecting.
content-boxBy default, most browsers use box-sizing: content-box. This means:
width and height apply only to the content area.Example:
cssdiv {
width: 200px;
padding: 20px;
border: 5px solid black;
}
Rendered size:
border-boxWith box-sizing: border-box, the padding and border are included within the declared width and height.
Updated example:
cssdiv {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid black;
}
Rendered size:
This makes layout calculations more intuitive and consistent, especially when creating grids, columns, and responsive layouts.
border-box GloballyTo avoid surprises, many developers apply box-sizing: border-box to all elements:
css/* Recommended global reset */
*,
*::before,
*::after {
box-sizing: border-box;
}
This ensures all elements, including pseudo-elements, follow the same predictable sizing model.
| Part | Description |
|---|---|
| Content | The inner part holding text/images |
| Padding | Inside spacing between content and border |
| Border | The outer line around padding and content |
| Margin | Outer space between the element and others |
box-sizing: border-box to simplify width and height calculations.With a solid grasp of the Box Model and smart use of box-sizing, your CSS layouts will be cleaner, more responsive, and easier to maintain.