The Box Model
Content, padding, border, and margin — how every element's size is actually calculated.
2 menit membaca
Every element on a page is a rectangular box, and CSS's "box model" describes what makes up that box's total size: content, padding, border, and margin, from the inside out.
The four layers
.card {
width: 300px;
padding: 20px;
border: 2px solid #cbd5e1;
margin: 16px;
}- Content — the actual text or child elements, sized by
width/height. - Padding — space inside the border, between the content and the border. It's part of the element's clickable/visible background.
- Border — a line drawn around the padding.
- Margin — space outside the border, separating this element from its neighbors. Margin is transparent and not part of the element's own background.
The size confusion, and box-sizing
By default, width sets the size of the content only — padding and border are added on top of it:
/* content-box (default) */
.card {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 2px solid black;
/* Rendered width: 300 + 20*2 + 2*2 = 344px */
}That's rarely what you want when laying out a page — you set width: 300px expecting a 300px box, and it renders wider. box-sizing: border-box fixes this by making width include padding and border:
.card {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 2px solid black;
/* Rendered width: 300px, padding and border eat into the content area */
}Because content-box sizing is so counterintuitive, almost every modern project sets border-box globally as one of the first rules in a stylesheet:
*,
*::before,
*::after {
box-sizing: border-box;
}Margin collapsing
.first {
margin-bottom: 20px;
}
.second {
margin-top: 30px;
}When two vertical margins meet between block elements (like the bottom margin of .first and top margin of .second stacked in normal flow), they don't add together — they collapse to the larger of the two, so the gap here is 30px, not 50px. This only happens with vertical margins in normal document flow; it doesn't apply to padding, to horizontal margins, or to elements using Flexbox or Grid (covered later), which is one reason many teams prefer those layout modes for predictable spacing.
Inspecting the box model
Every browser's DevTools has a box model diagram (in Chrome/Firefox, the Elements/Inspector panel's "Computed" or "Layout" tab) that shows the exact content, padding, border, and margin sizes for a selected element — it's the fastest way to debug "why is there extra space here" than guessing from the stylesheet alone.