Every single element rendered on a web page is treated by the browser engine as a rectangular box. The CSS Box Model is the core conceptual foundation that governs how the dimensions (width, height), internal spacing (padding), perimeter boundaries (borders), and external distances (margins) of every HTML element are calculated.
| Layer | Visual Role | Background Behavior | Key CSS Properties |
|---|---|---|---|
| 1. Content Area | The core interior where text, images, or nested child elements reside. | Inherits element background. | width, height, min-width |
| 2. Padding | Clear buffer space surrounding the content, pushing the border outward. | Filled by the element's background color. | padding, padding-inline, padding-block |
| 3. Border | The visible perimeter line enclosing the padding and content. | Has its own color, width, and style. | border, border-width, border-radius |
| 4. Margin | Completely transparent outer space separating this element from neighbors. | Always transparent (shows page background). | margin, margin: 0 auto; |
By default, browsers calculate dimensions using box-sizing: content-box. Under this legacy formula:
Total Rendered Width = width + padding-left + padding-right + border-left + border-right
If you set an element to width: 300px; padding: 20px; border: 5px solid black;, the actual rendered width on screen becomes 350px! This causes columns to break and responsive layouts to overflow mobile screens.
Modern frontend engineering fixes this permanently across all projects by setting box-sizing: border-box:
*, *::before, *::after {
box-sizing: border-box;
}
With border-box, if you specify width: 300px;, the padding and border are subtracted inward from the total size. The element remains exactly 300px wide, no matter how much padding or border you apply!
Question: An element has width: 200px; height: 100px; padding: 15px; border: 5px solid red; margin: 20px;. Calculate its total occupied width on the page under (a) content-box and (b) border-box.
Answer:
(a) Under content-box: Visible width = 200 (width) + 30 (padding) + 10 (border) = 240px. Total space occupied with margin = 240 + 40 (margin) = 280px.
(b) Under border-box: Visible width = 200px (padding and border fit inside). Total space occupied with margin = 200 + 40 = 240px.
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.