The CSS Box Model describes how every HTML element on a web page is treated as a rectangular box, which determines how space is calculated and how elements are displayed and interact with each other.
🧩 Structure of the Box Model
Each box consists of four main parts (from inside out):
+-----------------------------+
| Margin | ← Space outside the element
| +-----------------------+ |
| | Border | | ← Surrounds padding & content
| | +-----------------+ | |
| | | Padding | | | ← Space between content & border
| | | +-------------+ | | |
| | | | Content | | | | ← Text or image inside element
| | | +-------------+ | | |
| | +-----------------+ | |
| +-----------------------+ |
+-----------------------------+
⚙️ 1. Content
- The innermost area where text, images, or child elements are displayed.
- You can control its size with
widthandheight.
div {
width: 200px;
height: 100px;
}
⚙️ 2. Padding
- The space between the content and the border.
- It increases the size of the box but keeps the background color visible.
div {
padding: 20px;
}
⚙️ 3. Border
- Surrounds the padding (and content).
- You can style it with width, color, and type.
div {
border: 2px solid blue;
}
⚙️ 4. Margin
- The space outside the border.
- It creates distance between elements and doesn’t have background color.
div {
margin: 15px;
}
💡 Example
<div class="box">Hello World</div>
.box {
width: 200px;
padding: 10px;
border: 5px solid black;
margin: 15px;
}
📏 Total space taken horizontally:
width + padding-left + padding-right + border-left + border-right + margin-left + margin-right
= 200 + 10 + 10 + 5 + 5 + 15 + 15 = 260px
🧠 Bonus Tip — box-sizing
To make width include padding and border:
* {
box-sizing: border-box;
}
➡️ This makes layout management much easier!
✅ In short:
- Content → actual text/image
- Padding → space inside border
- Border → wraps the padding/content
- Margin → space outside the box