Web Analytics

The CSS Box Model

Beginner ~9 min read

What is the Box Model?

Every HTML element is a rectangular box. The CSS box model describes how these boxes are sized and spaced. Understanding this is crucial for layout and positioning.

The Four Parts

The box model consists of four areas, from inside to outside:

  1. Content - The actual content (text, images, etc.)
  2. Padding - Space between content and border
  3. Border - Line around the padding
  4. Margin - Space outside the border

Visualizing the Box Model

Let's see how padding, border, and margin create space around content.

HTML
CSS
JS
Pro Tip: Use browser DevTools to inspect the box model. Right-click any element and select "Inspect" to see its box model diagram.

Total Element Size

By default, the total width of an element is calculated as:
total width = width + padding-left + padding-right + border-left + border-right

HTML
CSS
JS

Box-Sizing Property

The box-sizing property changes how width and height are calculated. border-box includes padding and border in the width, making sizing much easier.

HTML
CSS
JS
Best Practice: Most developers use box-sizing: border-box globally for easier, more predictable layouts. Add this to your CSS reset:
* { box-sizing: border-box; }

Key Concepts

  • Every element is a box with content, padding, border, and margin
  • Default: width/height only applies to content area
  • box-sizing: border-box includes padding and border in width/height
  • Margin creates space between elements
  • Padding creates space inside the element

Quick Quiz

Which box-sizing value includes padding and border in the element's width?

A
content-box
B
border-box
C
padding-box
D
margin-box