The CSS Box Model is a fundamental concept that describes how every HTML element is structured and how spacing is calculated around it.
🔹 Box Model Structure:
Every element is represented as a rectangle made up of 4 parts (from innermost to outermost):
- Content – The actual text, image, or data inside the element.
- Padding – Clears space inside the element, between the content and the border.
- Border – A visible boundary surrounding the padding and content.
- Margin – Clears space outside the element, between it and other elements.
📦 Visual Diagram:
+----------------------------+
| Margin |
| +----------------------+ |
| | Border | |
| | +----------------+ | |
| | | Padding | | |
| | | +----------+ | | |
| | | | Content | | | |
| | | +----------+ | | |
| | +----------------+ | |
| +----------------------+ |
+----------------------------+
🔹 Example in CSS:
.box {
margin: 20px;
border: 2px solid black;
padding: 10px;
width: 200px;
}
📐 Total Width Calculation:
Total width = margin + border + padding + content
- If
box-sizing: content-box, padding and border are added outside the width. - If
box-sizing: border-box, padding and border are included inside the width.