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.
Component "BoxModelVisualizer" is not available. Please define it in the MDX components.
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:
div {
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:
div {
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:
/* 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.