#css
#tutorial
#beginner
Day 3: The Box Model
Day 3: Thinking Inside the Box
Every single element in HTML is a rectangular box. Understanding this box is key to layout.
The 4 Layers
From inside out:
- Content: The text or image itself.
- Padding: Space inside the box (between content and border). Background color applies here.
- Border: The line around the padding.
- Margin: Space outside the box (pushes other elements away). Transparent.
.box {
content: "Hi";
padding: 20px; /* Internal breathing room */
border: 5px solid black; /* The shell */
margin: 50px; /* Personal space */
}
The “Math Problem” (Box Sizing)
By default, CSS adds padding and border TO the width.
If you set width: 200px + padding: 20px + border: 5px:
Total Width = 200 + 20 + 20 + 5 + 5 = 250px.
This is annoying.
The Solution: border-box
Always reset this setting at the top of your CSS file. It tells the browser: “If I say 200px, I mean 200px TOTAL. Squeeze the padding inside.”
/* Apply to EVERYTHING */
*, *::before, *::after {
box-sizing: border-box;
}
Auto Margins
Want to center a block horizontally?
.container {
width: 800px;
margin-left: auto;
margin-right: auto;
/* Shorthand: */
margin: 0 auto;
}
Homework for Day 3:
- Draw the box model on a piece of paper (seriously, it helps).
- Create two boxes in HTML.
- Give them thick borders and large padding.
- Experiment with
box-sizing: content-boxvsborder-boxto see the size change.
Day 4: Making text beautiful with Typography!