The CSS Box Model
Learning Objectives
- Understand content, padding, border and margin.
- Calculate an element's total dimensions.
- Understand margin collapsing.
- Use box-sizing for predictable layouts.
1. What Is the Box Model?
Every CSS element is represented by one or more boxes. The traditional CSS box model has four main areas: content, padding, border and margin.
- Content: Text, images or other content inside the element.
- Padding: Space between the content and border.
- Border: The line surrounding the padding and content.
- Margin: Space outside the border separating neighboring boxes.
2. Basic Example
.box {
width: 200px;
padding: 20px;
border: 5px solid navy;
margin: 15px;
}With the default content-box sizing, the content width is 200px. Horizontal padding adds 40px and horizontal borders add 10px, producing a border-box width of 250px. The left and right margins add another 30px to the space occupied in a simple horizontal layout.
3. Calculate the Total Width
With box-sizing: content-box:
Total border-box width = content width + left/right padding + left/right borders.
In the example: 200 + 40 + 10 = 250px.
4. Using box-sizing: border-box
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid navy;
}Here, the declared 200px width includes content, padding and borders. The content area becomes 150px wide. Margins remain outside the border box.
5. A Common Project Reset
*,
*::before,
*::after {
box-sizing: border-box;
}This makes width calculations more predictable for most components.
6. Margin Collapsing
In certain block formatting contexts, vertical margins between adjacent block elements can collapse rather than add together. For example, a bottom margin of 20px and a top margin of 30px can produce a 30px gap rather than 50px. Margin collapsing does not apply in the same way to flex and grid items.
7. Padding and Margin Shorthand
.one { margin: 10px; }
.two { padding: 10px 20px; }
.three { margin: 5px 10px 15px 20px; }One value applies to all sides. Two values mean vertical then horizontal. Three values mean top, horizontal, bottom. Four values follow top, right, bottom, left.