Chapter 09 of 33

The Box Model

Here is one of the most important ideas in all of CSS: every element on a web page is a rectangular box. A heading is a box, a paragraph is a box, an image is a box, even a single <span> word inside a sentence is a box. Layout in CSS is simply the art of sizing these boxes and placing them next to or inside each other.

The box model describes what each box is made of and how its final size is calculated. If you have ever set width: 300px and found your element was actually 350px wide, or a layout broke because two "50%" columns didn't fit side by side, the box model is the reason. Let's understand it properly.


The Four Areas of a Box

The CSS box model describes every element as a rectangle made of four nested areas: the content area, surrounded by padding, then a border, then a margin.

┌────────────────────────────────────────────┐
│                  MARGIN                    │  transparent space outside
│   ┌────────────────────────────────────┐   │
│   │              BORDER                │   │  the visible frame
│   │   ┌────────────────────────────┐   │   │
│   │   │          PADDING           │   │   │  space inside the frame
│   │   │   ┌────────────────────┐   │   │   │
│   │   │   │      CONTENT       │   │   │   │  text, images, children
│   │   │   └────────────────────┘   │   │   │
│   │   └────────────────────────────┘   │   │
│   └────────────────────────────────────┘   │
└────────────────────────────────────────────┘
AreaWhat it isBackground shows here?Property
ContentWhere text and child elements are drawnYeswidth, height
PaddingBreathing room between content and borderYespadding
BorderA line around the paddingBorder has its own colour (background shows under dashed/dotted gaps)border
MarginSpace between this box and its neighboursNo, always transparentmargin

A simple real-world analogy: a framed photograph on a wall. The photo is the content, the white mount card around it is the padding, the wooden frame is the border, and the empty wall space you leave between it and the next frame is the margin.

Each area also has an outer edge with a name you will see in specifications and DevTools: the content edge, padding edge, border edge and margin edge. The rectangles they enclose are called the content box, padding box, border box and margin box.


A First Example

.card {
  width: 300px;
  padding: 20px;
  border: 5px solid #1e3a8a;
  margin: 30px;
  background-color: #dbeafe;
}
<div class="card">I am a card. My content box is 300px wide.</div>

In the browser you see a light blue box with a dark blue frame, surrounded by 30px of empty margin. (Measured in Chrome, its left edge sits 38px from the window: the card's 30px margin plus the <body> element's default 8px margin. At the top it is only 30px, because the two top margins touch and collapse into one, a rule we meet at the end of this chapter.) The light blue fills the content and padding area, and the margin is empty, showing the page behind.

Now the important question: how wide is this card on screen? Not 300px.


Calculating the Size: box-sizing: content-box

By default, width and height set the size of the content box only. Padding and border are added on top. This default is called box-sizing: content-box.

Worked example

Visible width (border box)
  = border-left + padding-left + width + padding-right + border-right
  = 5 + 20 + 300 + 20 + 5
  = 350px

Space taken in the layout (margin box)
  = margin-left + 350 + margin-right
  = 30 + 350 + 30
  = 410px

Measuring the element in Chrome with getBoundingClientRect() (which reports the border box) gives exactly 350. Height works the same way: if the content is 40px tall, the border box is 5 + 20 + 40 + 20 + 5 = 90px.

The general formula for the content-box model:

total width  = margin-left + border-left + padding-left + width
               + padding-right + border-right + margin-right

total height = margin-top + border-top + padding-top + height
               + padding-bottom + border-bottom + margin-bottom

This is a frequent exam question. Read it carefully: is the question asking for the visible width (border box) or the space occupied (margin box)?


The Fix Everyone Uses: box-sizing: border-box

Content-box sizing is awkward. If a designer says "this card is 300px wide", you have to subtract padding and border yourself. Change the padding and the card changes size.

With box-sizing: border-box, width and height describe the border box. Padding and border are taken from inside that size, and the content box shrinks to fit:

.card {
  box-sizing: border-box;
  width: 300px;
  padding: 20px;
  border: 5px solid #1e3a8a;
  margin: 30px;
}
Visible width (border box) = 300px            ← exactly what you wrote
Content width              = 300 − 2×20 − 2×5 = 250px
Space taken with margin    = 30 + 300 + 30    = 360px

Chrome measures the border box as exactly 300. The margin is still added outside; border-box only includes padding and border.

content-box (default)border-box
width meansContent width onlyContent + padding + border
Adding paddingMakes the box biggerShrinks the content, box stays the same
Visible width for width 300, padding 20, border 5350px300px
Includes margin?NoNo
Used byBrowser default for most elementsAlmost every modern project and CSS framework

Why it matters: the 100% overflow problem

Suppose you want an input box to fill its 600px-wide container, with some padding inside:

.container { width: 600px; }
.field {
  width: 100%;
  padding: 20px;
  border: 2px solid;
}
content-box: 600 + 2×20 + 2×2 = 644px   → sticks out 44px past the container!
border-box:  600px                       → fits perfectly

Chrome confirmed: 644px with the default, 600px with border-box. The same issue is behind "two 50% columns with padding don't fit side by side".

The standard reset

Almost every professional style sheet starts with:

*,
*::before,
*::after {
  box-sizing: border-box;
}

The pseudo-elements are listed separately because the universal selector * does not match ::before and ::after. You will see this rule at the top of most CSS you read from now on, and the rest of this tutorial assumes it unless stated otherwise.

Note: some form elements, such as <button>, <select> and some <input> types, already use border-box in browser default styles. The reset makes everything consistent.


How width: auto Works for Block Boxes

If you don't set a width, a block element such as <div>, <p> or <section> has width: auto. For a block box in normal flow, auto means: fill the available width of the containing block, after margins, borders and padding are subtracted.

Containing block width:  600px
margin 10 + border 2 + padding 20 on each side

width:auto content = 600 − 2×(10 + 2 + 20) = 536px
border box         = 600 − 2×10            = 580px
Never overflows.

This is why width: auto is usually better than width: 100% for blocks: it automatically accounts for margin, border and padding, whatever box-sizing is. Reach for width: 100% only when you need it, such as for inputs or images.

Height is different. height: auto means "as tall as the content needs". That is why boxes grow when you add text, and why a height: 50% child of an auto-height parent has nothing to calculate from (as you saw in CSS Units).


Minimum and Maximum Sizes

Fixed widths and heights are fragile. The min- and max- properties set limits instead:

PropertyEffect
min-widthThe box can never be narrower than this
max-widthThe box can never be wider than this
min-heightNever shorter; can still grow with content
max-heightNever taller; extra content overflows
.article {
  max-width: 700px;   /* full width on phones, at most 700px on big screens */
}
.hero {
  min-height: 400px;  /* at least 400px tall, but grows if text needs more room */
}
img {
  max-width: 100%;    /* images never overflow their container */
  height: auto;       /* keep the aspect ratio */
}

When they conflict, the rules are applied in this order: width is limited by max-width, and then min-width wins over both. So with width: 500px; max-width: 300px; min-width: 400px the result is 400px. The same applies to heights.

Prefer min-height over height for containers of text. With a fixed height, when a user enlarges the font or a translation is longer, text spills out of the box (what happens next is the topic of Overflow & Scrolling).

A related property, aspect-ratio, lets the browser compute one dimension from the other: aspect-ratio: 16 / 9; width: 100%; gives a video-shaped box at any width.


Block Boxes vs Inline Boxes

The box model applies to every element, but the type of box changes how its parts behave. The display property controls this; you will study it fully in The Display Property. For now, know the two basic kinds:

  • Block boxes (div, p, h1, section, ul...) start on a new line and stack vertically.

  • Inline boxes (span, a, strong, em...) sit inside a line of text and flow with it.

Inline boxes follow the box model only partly:

.tag {
  padding: 10px;
  margin: 20px;
  border: 2px solid black;
  background-color: gold;
}
<p>This is a paragraph of text with an <span class="tag">inline span</span>
sitting in the middle of it.</p>

What we saw in Chrome's screenshot:

  • Horizontal margin and padding work: there is clear space between the gold box and the words before and after it.

  • Vertical padding and border are painted, but the lines of text do not move apart. The gold box overlaps the line above and the line below.

  • Vertical margin has no visible effect at all.

  • When the span wrapped onto two lines, the left padding and border appeared only at its start and the right ones only at its end, as if the box had been sliced in two.

Block boxInline box
width / heightRespectedIgnored (size comes from the text)
Horizontal padding, border, marginRespectedRespected
Vertical padding and borderPush other content awayPainted, but don't push lines apart
Vertical marginRespectedNo effect
Starts on a new lineYesNo

If you need an element that sits in a line of text but fully respects width, height and vertical spacing (a button-like link, for example), use display: inline-block. Replaced elements such as <img> are a special case: they are inline, but width and height do apply to them.


What Doesn't Change the Box Size

A few things look like part of the box but don't take up layout space:

  • outline is drawn outside the border but takes no space and never moves other elements. That's why it's used for focus rings. Details in Borders & Outlines.

  • box-shadow is painted outside the box without affecting layout (see Shadows & Filters).

  • transform (scale, rotate, translate) changes how the box is drawn, not the space it reserves (see Transforms).


Margins Can Collapse

One more box-model rule you must be aware of: when the vertical margins of two block boxes touch, they can collapse into a single margin instead of adding up. Two paragraphs with margin: 16px 0 have 16px between them, not 32px. This is called margin collapsing. It only affects vertical margins of block boxes in normal flow, and it is explained step by step in the next chapter, Margin & Padding.


Seeing the Box Model in DevTools

Right-click any element and choose Inspect. In Chrome's Computed tab (or Firefox's Layout tab) you will find a diagram of nested rectangles labelled margin, border, padding and the content size, with the actual pixel numbers. Hovering an element in the Elements panel also highlights its areas on the page: content in blue, padding in green, border in yellow, margin in orange. Whenever a size isn't what you expected, check this diagram first.


Common Mistakes

  • Forgetting padding and border add to width under the default content-box. Use the border-box reset.

  • Thinking border-box includes the margin. It doesn't; margin is always outside.

  • Using width: 100% on blocks with margin or padding and getting overflow. Leave width as auto.

  • Setting width or height on a <span> or <a> and seeing no change. Inline boxes ignore them; use inline-block.

  • Giving text containers a fixed height. Use min-height so content can grow.

  • Expecting the background to fill the margin. Margins are always transparent; use padding for coloured space.

  • Writing * { box-sizing: border-box; } only, which misses ::before and ::after.


Interview / Exam Questions

1. A div has width: 200px; padding: 15px; border: 3px solid; margin: 10px; with the default box-sizing. What is its visible width and the total horizontal space it occupies?

Visible (border box): 3 + 15 + 200 + 15 + 3 = 236px. Total including margin: 10 + 236 + 10 = 256px.

2. Same div with box-sizing: border-box. What are the visible width and the content width?

Visible width = 200px. Content width = 200 − 2×15 − 2×3 = 164px. Total space with margin = 220px.

3. What is the difference between content-box and border-box?

In content-box, width/height size only the content area and padding plus border are added outside it. In border-box, width/height include padding and border, so the content area shrinks. Neither includes margin.

4. Why doesn't height: 200px work on a <span>?

A span is a non-replaced inline element; its height is determined by its font and line-height, and width/height are ignored. Change it to display: inline-block or block.

5. An element has width: 800px; max-width: 600px; min-width: 700px. What is its width?

max-width clamps 800 down to 600, then min-width overrides max-width, giving 700px.

6. Which parts of the box show the element's background?

The content and padding areas, and also under the border (visible through dashed or dotted borders). The margin is always transparent.


Summary

  • Every element is a box with four areas: content, padding, border, margin.

  • With the default content-box, visible width = width + padding + border; margin is extra space outside.

  • With border-box, width already includes padding and border, which is why the *, *::before, *::after { box-sizing: border-box; } reset is standard.

  • Block boxes with width: auto fill their container safely; height: auto fits the content.

  • Use min-/max- sizes instead of fixed sizes; min-width beats max-width.

  • Inline boxes ignore width and height, and their vertical padding/margin don't push lines apart.

  • Outlines, shadows and transforms don't change the space a box takes.

In the next chapter, Margin & Padding, we look closely at the two spacing properties: shorthands, centring with auto, negative margins, and the famous margin collapsing rules.