HomeGuidesHTML & CSSCSS Box Model Explained — margin, padding, border & box-sizing
🎨 HTML & CSS

CSS Box Model: margin, padding, border, and box-sizing

The box model controls every element's size. Here's what front-end exams test — box-sizing and margin collapse.

Examifyr·2026·5 min read

The four layers

Every element has content, padding, border, and margin. The default box model adds padding and border TO the content width.

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
    margin: 10px;
}

/* Default (content-box): */
/* Total width = 200 + 20 + 20 + 5 + 5 = 250px */
/* width only sets the content area */

/* border-box (intuitive): */
/* Total width = 200px (includes padding and border) */
/* Content area = 200 - 20 - 20 - 5 - 5 = 150px */
Note: This is why most projects add * { box-sizing: border-box } globally — it makes sizing predictable.

box-sizing: border-box

border-box makes width include padding and border, which is far more intuitive for layout.

/* Apply globally (standard practice) */
*, *::before, *::after {
    box-sizing: border-box;
}

.card {
    width: 300px;
    padding: 24px;
    border: 1px solid #ccc;
    /* With border-box: total is exactly 300px */
    /* Without border-box: total would be 350px */
}

Margin shorthand

Margin and padding shorthand can take 1, 2, 3, or 4 values.

/* 1 value: all sides */
margin: 10px;

/* 2 values: top/bottom, left/right */
margin: 10px 20px;

/* 3 values: top, left/right, bottom */
margin: 10px 20px 30px;

/* 4 values: top, right, bottom, left (clockwise) */
margin: 10px 20px 30px 40px;

/* Center horizontally */
.container {
    width: 800px;
    margin: 0 auto;  /* top/bottom: 0, left/right: auto */
}

Margin collapse

When two vertical margins meet, they collapse to the larger value — they don't add.

.paragraph-1 {
    margin-bottom: 30px;
}

.paragraph-2 {
    margin-top: 20px;
}

/* Space between them: 30px (NOT 50px) */
/* The margins collapse to the larger value */

/* Margin collapse does NOT happen with: */
/* - horizontal margins */
/* - flexbox/grid items */
/* - floated elements */
/* - elements with padding or border between them */
Note: Margin collapse is a classic exam question. It only applies to vertical (top/bottom) margins between block elements in normal flow.

Exam tip

The box-sizing question is always asked: "What's the difference between content-box and border-box?" — content-box: width is content only, padding/border add to it. border-box: width includes padding and border.

🎯

Think you're ready? Prove it.

Take the free HTML & CSS readiness test. Get a score, topic breakdown, and your exact weak areas.

Take the free HTML & CSS test →

Free · No sign-up · Instant results

← Previous
CSS Selectors Explained — Specificity, Pseudo-classes & Combinators
Next →
CSS Flexbox Explained — justify-content, align-items & Flex Properties
← All HTML & CSS guides