๐ฆ CSS Box Model – Complete Guide with Examples & Math
Understanding layout in CSS starts with one fundamental concept: the box model. Every element you see on a webpage is essentially a rectangular box.
๐ Table of Contents
- Content
- Padding
- Border
- Margin
- Box Model Math
- Complete Example
- Rendered Output
- Key Takeaways
- Related Articles
๐งฑ 1. Content Area
This is where your actual content lives (text, images, etc.).
div {
width: 300px;
height: 200px;
}
๐ This defines only the content size—not the full box.
๐ 2. Padding
Padding adds space inside the box, between content and border.
div {
padding: 20px;
}
You can also control each side:
div {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;
}
๐งฉ 3. Border
The border wraps around padding and content.
div {
border: 5px solid black;
}
Different borders per side:
div {
border-top: 3px dotted red;
border-right: 4px solid blue;
border-bottom: 2px dashed green;
border-left: 6px double black;
}
๐ 4. Margin
Margin creates space outside the box.
div {
margin: 30px;
}
Individual margins:
div {
margin-top: 20px;
margin-right: 10px;
margin-bottom: 15px;
margin-left: 25px;
}
⚠️ Margin Collapse Explained
If two vertical margins meet, they may combine instead of adding.
๐ Box Model Math (Easy Explanation)
The total size of an element is:
\[ Total\ Width = Content + Padding + Border + Margin \]
More precisely:
\[ Total\ Width = W + (P_L + P_R) + (B_L + B_R) + (M_L + M_R) \]
Simple Example:
- Content width = 300px
- Padding = 20px each side → 40px
- Border = 5px each side → 10px
- Margin = 30px each side → 60px
\[ Total = 300 + 40 + 10 + 60 = 410px \]
๐ป Complete Example
div {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
๐ฅ️ Visual Output (Conceptual)
Click to Expand
| Margin (30px) |
| Border (5px) |
| Padding (20px) |
| Content (300px) |
⚡ Bonus: box-sizing
To avoid size confusion, use:
* {
box-sizing: border-box;
}
๐ก Key Takeaways
- Every element is a box
- Padding and border increase size
- Margin controls spacing outside
- Math helps avoid layout bugs
- Use box-sizing for easier layouts
๐ฏ Final Thoughts
The box model is the foundation of CSS layouts. Once you truly understand it, everything from spacing to alignment becomes much easier.
Master this concept, and your frontend skills will improve dramatically.
No comments:
Post a Comment