css - CSS Box Model
The CSS Box Model is a fundamental concept that describes how elements are structured and rendered on a web page. It defines how space is calculated around HTML elements.
Every element is essentially a rectangle (a “box”), and the box model breaks this rectangle into four parts:
Parts of the CSS Box Model
-
Content
-
The actual content of the box (text, images, etc.)
-
Controlled by
width
andheight
-
-
Padding
-
Space inside the box, around the content
-
Increases the spacing between the content and the border
-
Transparent
-
-
Border
-
The line surrounding the padding (and content)
-
Controlled with
border-width
,border-style
, andborder-color
-
-
Margin
-
Space outside the box, separating it from other elements
-
Also transparent
-
Visual Diagram
+-----------------------------+
| Margin |
| +----------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +--------+ | | |
| | | | Content | | | |
| | | +--------+ | | |
| | +---------------+ | |
| +----------------------+ |
+-----------------------------+
Example
.box { width: 200px; height: 100px; padding: 20px; border: 5px solid black; margin: 15px; }
Total space occupied by.box
:
Width = 200 (content) + 2×20 (padding) + 2×5 (border) + 2×15 (margin) = 280px + 30px = 310px
Why the Box Model Matters
-
Controls layout spacing
-
Prevents overflow/layout shifts
-
Helps you design precise, responsive UIs