π¦ CSS COURSE β MODULE 5: BOX MODEL
π File: box-model.md
π¦ CSS Box Model
π Introduction
Every HTML element in CSS is treated like a box.
This box controls:
- size
- spacing
- borders
- layout behavior
π If you donβt understand the box model, CSS will feel confusing.
π§± 1. The Box Model Structure
Every element is made of:
+------------------------+
| Margin |
| +------------------+ |
| | Border | |
| | +------------+ | |
| | | Padding | | |
| | | Content | | |
| | +------------+ | |
| +------------------+ |
+------------------------+
π 2. Content
div {
width: 200px;
height: 100px;
}
β This is the actual content area
π§© 3. Padding (Inside spacing)
div {
padding: 20px;
}
β Space inside the box β Pushes content away from border
π§± 4. Border
div {
border: 2px solid black;
}
β Visible line around element
π¦ 5. Margin (Outside spacing)
div {
margin: 20px;
}
β Space between elements
β οΈ VERY IMPORTANT RULE
By default:
width = content only (NOT full box)
π§ 6. Box Sizing (BEST PRACTICE)
* {
box-sizing: border-box;
}
β Includes padding + border inside width β Makes layout easier
π§© Real Example
<div class="box">Hello CSS Box Model</div>
.box {
width: 200px;
padding: 20px;
border: 2px solid black;
margin: 20px;
}
π§ What happens?
- Content = 200px width
- Padding adds inside space
- Border surrounds it
- Margin pushes it away from other elements
π Box Model vs Real Layout
| Part | Purpose |
|---|---|
| Content | text/image |
| Padding | inner spacing |
| Border | outline |
| Margin | outer spacing |
β οΈ Common Mistakes
- Confusing margin vs padding β
- Forgetting box-sizing β
- Not understanding spacing behavior β
- Overusing margins everywhere β
π― Pro Tip
π Most modern websites ALWAYS use:
* {
box-sizing: border-box;
}
β This prevents layout bugs
π§ͺ Mini Exercise
Create a page with:
- A box with width 300px
- Add padding 20px
- Add border 3px solid
- Add margin around it
- Change background color