Quest 1 โข Lesson 8
๐ฆ CSS Box Model
Every element in CSS is a rectangular box. The Box Model consists of four layers: content, padding, border, and margin.
"Understanding the box model is essential for creating layouts. It determines how much space an element takes up and how it interacts with neighbouring elements."
๐งฉ The Four Layers
๐ฆ Content
๐จ Padding
๐ฅ Border
๐ฉ Margin
CONTENT
Padding (yellow) ยท Border (red) ยท Margin (green)
box-model.css
.box {
/* content area */
width: 200px;
height: 100px;
/* padding inside the border */
padding: 20px;
/* border around padding */
border: 5px solid #ef4444;
/* margin outside the border */
margin: 30px;
}
/* content area */
width: 200px;
height: 100px;
/* padding inside the border */
padding: 20px;
/* border around padding */
border: 5px solid #ef4444;
/* margin outside the border */
margin: 30px;
}
๐ `box-sizing: border-box` vs `content-box`
By default, box-sizing: content-box means width/height apply only to content. Padding and border are added on top.
With box-sizing: border-box, width/height include padding and border โ much easier for layouts.
content-box (default)
200px wide + padding + border = 228px
border-box
200px wide includes padding + border
โจ Challenge: Build a Card with Box Model
Create a card (div) with:
- Content: "My Card" text
- Padding: 1rem (all sides)
- Border: 2px solid #3b82f6
- Margin: 1rem (all sides)
- Use
border-boxso width is predictable
.card {
box-sizing: border-box;
padding: 1rem;
border: 2px solid #3b82f6;
margin: 1rem;
background: #1e293b;
color: white;
border-radius: 0.5rem;
}
<div class="card">My Card</div>
box-sizing: border-box;
padding: 1rem;
border: 2px solid #3b82f6;
margin: 1rem;
background: #1e293b;
color: white;
border-radius: 0.5rem;
}
<div class="card">My Card</div>
โค๏ธ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
โ Buy Me a Coffeeโก๏ธ Ready for more?
Next lesson: Flexbox & Grid โ build modern layouts.
Continue to Lesson 1.9 โ(Coming soon โ check back or buy Pro Pack for instant access)