What is the CSS Box Model?
Every HTML element is represented as a box. The CSS box model defines how the size and spacing of elements are calculated.
Box Model Structure
- Content – The actual content (text, image)
- Padding – Space inside the element
- Border – Surrounds padding and content
- Margin – Space outside the element
Example
CSSRead-only
1
Total Width Calculation
Total Width = Content + Padding + Border + Margin
TEXTRead-only
1
Box Sizing
The box-sizing property controls how width and height are calculated.
CSSRead-only
1
Box-Sizing Types
| Value | Description |
|---|---|
| content-box | Default (padding & border added) |
| border-box | Includes padding & border in width |
Visual Understanding
Think of the box model as layers: content at the center, surrounded by padding, then border, and finally margin.
Best Practices
- Use box-sizing: border-box for easier layout
- Maintain consistent spacing
- Understand margin vs padding usage
- Avoid unexpected overflow issues
Common Mistakes
- Forgetting padding affects total size
- Confusing margin and padding
- Not using border-box
- Miscalculating layout width
Conclusion
The CSS box model is fundamental for layout design. Mastering it helps build accurate and responsive UI layouts.