GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

📦 Lesson 3: The CSS Box Model

⏱️ Estimated time: 25 minutes | Difficulty: Beginner

Everything is a Box

In CSS, every element is considered a rectangular box. Understanding the box model is the key to creating layouts.

Every Element is a Box!

Every HTML element is surrounded by 4 layers: Content → Padding → Border → Margin

Margin (outside space)
Border
Padding (inside space)
Content
.box {
    width: 300px;
    padding: 20px;        /* Inside spacing */
    border: 2px solid #ff2d95;
    margin: 30px;         /* Outside spacing */

    /* Total width = 300 + 20*2 + 2*2 + 30*2 = 404px! */
}

/* Fix with box-sizing */
* {
    box-sizing: border-box;  /* Width INCLUDES padding & border */
}
/* Now .box total width = 300px + 30*2 margin = 360px */

Margin Shortcuts

margin: 10px;              /* All 4 sides */
margin: 10px 20px;         /* Top/Bottom  Left/Right */
margin: 10px 20px 30px;    /* Top  Left/Right  Bottom */
margin: 10px 20px 30px 40px; /* Top Right Bottom Left */

margin: 0 auto;            /* Center horizontally! */

/* Same pattern works for padding */
padding: 1rem 2rem;

Display Property

display: block;        /* Full width, new line (div, p, h1) */
display: inline;       /* Content width only (span, a) */
display: inline-block; /* Inline but with width/height */
display: none;         /* Hidden completely */

✅ Quick Quiz

❓ What does box-sizing: border-box do?

❓ How do you center an element horizontally?

❓ What are the 4 box model layers in order (outside to inside)?

← Previous Next: Flexbox →