Know if you're actually ready. Take the HTML & CSS quiz → get your AI readiness report.Take the free test →

Study guide · 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.

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 */
NoteThis 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 */
NoteMargin collapse is a classic exam question. It only applies to vertical (top/bottom) margins between block elements in normal flow.
Exam tipThe 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.

Want a person to help?

Struggling with HTML & CSS? Work 1:1 with a vetted HTML & CSS tutor on Wyzant. (affiliate link)

Find a HTML & CSS tutor →
← All HTML & CSS guides