Skip to main content

What is the CSS Box Model?

Answer

The CSS Box Model is the foundation of layout in CSS. Every HTML element is represented as a rectangular box consisting of four areas: content, padding, border, and margin.

Box Model Diagram

The Four Areas

AreaDescriptionAffected by
ContentThe actual content (text, images)width, height
PaddingSpace between content and borderpadding
BorderThe border around paddingborder, border-width
MarginSpace outside the bordermargin

Example

.box {
width: 200px; /* Content width */
height: 100px; /* Content height */
padding: 20px; /* All sides */
border: 5px solid black;
margin: 10px;
}

Total Size Calculation (content-box)

Total Width = width + padding-left + padding-right + border-left + border-right
Total Width = 200 + 20 + 20 + 5 + 5 = 250px

Total Height = height + padding-top + padding-bottom + border-top + border-bottom
Total Height = 100 + 20 + 20 + 5 + 5 = 150px

box-sizing Property

/* Default behavior */
.content-box {
box-sizing: content-box; /* Default */
width: 200px;
padding: 20px;
/* Total width: 240px */
}

/* Easier to work with */
.border-box {
box-sizing: border-box;
width: 200px;
padding: 20px;
/* Total width: 200px (content shrinks to 160px) */
}

/* Best practice: Apply to all elements */
*,
*::before,
*::after {
box-sizing: border-box;
}

Margin Collapsing

When vertical margins of adjacent elements touch, they collapse into a single margin (the larger one wins):

<div style="margin-bottom: 30px;">Box 1</div>
<div style="margin-top: 20px;">Box 2</div>
<!-- Space between = 30px (not 50px) -->

Margin collapsing happens:

  • Between adjacent siblings
  • Between parent and first/last child (if no padding/border separates them)
  • On empty blocks

Inspecting in DevTools

Open DevTools → Elements → Computed tab to see the box model visualization with actual calculated values.

Key Points

  • Every element is a box with content, padding, border, margin
  • box-sizing: border-box makes width/height include padding and border
  • Vertical margins can collapse
  • Margin can be negative, padding cannot
  • Use DevTools to visualize the box model