The Box Model

Table of Contents

  1. Everything Is a Box
  2. Content, Padding, Border, Margin
  3. Shorthand for Four Sides
  4. box-sizing: the Setting You Always Want
  5. Width and Height
  6. The display Property
  7. Margin Collapse
  8. Units
  9. Spacing the Profile Page
  10. Try It Yourself

1. Everything Is a Box

To the browser, every element — paragraph, link, image, even a single word of text — is a rectangular box. Layout in CSS is the art of sizing those boxes, spacing them, and placing them next to each other.

You can see it in DevTools. Hover over any element in the Elements panel and the page highlights a colored rectangle: blue for the content, green for padding, orange for margin. On the right of the Styles pane there's a Computed tab with a diagram of the box and its exact measurements. Once you can see the boxes, most layout mysteries disappear.

2. Content, Padding, Border, Margin

Each box has four layers, from the inside out:

┌──────────────────────────────────┐
│             margin               │   space OUTSIDE the border
│   ┌──────────────────────────┐   │
│   │          border          │   │   the edge line
│   │   ┌──────────────────┐   │   │
│   │   │     padding      │   │   │   space INSIDE the border
│   │   │   ┌──────────┐   │   │   │
│   │   │   │ content  │   │   │   │   the text or image
│   │   │   └──────────┘   │   │   │
│   │   └──────────────────┘   │   │
│   └──────────────────────────┘   │
└──────────────────────────────────┘
LayerPropertyWhat it does
Contentwidth, heightThe text or image itself
PaddingpaddingSpace between the content and the border. Shows the element's background
BorderborderA line around the padding
MarginmarginSpace between this box and its neighbors. Always transparent

The question to ask: "is this space part of the thing, or between things?" Part of it — inside a button, between the text and the edge — is padding. Between it and its neighbor is margin.

.card {
  padding: 16px;
  border: 1px solid #d6d3d1;
  margin-bottom: 24px;
}

A border takes three values: width, style, color (1px solid #d6d3d1). Other styles are dashed and dotted. border-radius rounds the corners, and border-radius: 50% turns a square image into a circle.

3. Shorthand for Four Sides

margin and padding can be written for each side (margin-top, margin-right, margin-bottom, margin-left) or in shorthand. The order goes clockwise from the top: top, right, bottom, left.

padding: 16px;                /* all four sides */
padding: 8px 16px;            /* top & bottom 8, left & right 16 */
padding: 8px 16px 24px;       /* top 8, left & right 16, bottom 24 */
padding: 8px 16px 24px 32px;  /* top, right, bottom, left */

To center a block horizontally, give it a width and set the side margins to auto:

main {
  max-width: 800px;
  margin: 0 auto;
}

4. box-sizing: the Setting You Always Want

Here's a trap. If you set width: 300px and padding: 20px and border: 2px solid, how wide is the box?

By default (box-sizing: content-box), the width applies only to the content. The padding and border get added: 300 + 20 + 20 + 2 + 2 = 344px. Layouts with two 50% boxes plus padding overflow their container because of this.

The fix is box-sizing: border-box, which makes width include padding and border — a 300px box is 300px wide, period. Every professional stylesheet starts with this reset:

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

Put it at the top of style.css now. It's the first rule in almost every project, including this website's.

5. Width and Height

  • Block elements take the full available width by default. You normally leave width alone and let them fill their container.
  • Height is normally not set. The box grows to fit its content, so text never overflows. Fixed heights are a common source of broken layouts.
  • max-width is the most useful: "as wide as needed, but never wider than this." It lets a layout shrink on small screens.
  • min-width, min-height, and max-height also exist.
img {
  max-width: 100%;
  height: auto;
}

That small rule on images stops them from overflowing their container and keeps their proportions. It's the first step of responsive design, and chapter 11 returns to it.

When content is bigger than its box, the overflow property decides what happens: visible (default, spills out), hidden (cut off), scroll, or auto (scrollbars only when needed).

6. The display Property

Chapter 3 introduced block and inline. The display property controls which one an element is.

ValueBehavior
blockStarts on a new line, fills the width, honors width/height/margins
inlineFlows inside a line of text. Ignores width, height, and vertical margin
inline-blockFlows inline like text, but accepts width, height, and padding
noneRemoved from the page completely, as if it wasn't in the HTML
flex, gridLays out children with Flexbox or Grid — chapters 9 and 10

A common use: making links look like buttons. A plain <a> is inline, so its vertical padding won't push other things away. Make it inline-block:

.button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #b45309;
  color: #ffffff;
  text-decoration: none;
  border-radius: 6px;
}

display: none hides an element from everyone, including screen readers. To hide something visually but keep it for assistive tools, use the "visually hidden" technique with position and tiny sizes. Skip links, mentioned in chapter 4, are one example.

7. Margin Collapse

Margins behave in a surprising way. When two vertical margins touch, they don't add — they collapse into the larger one:

h2 { margin-bottom: 24px; }
p  { margin-top: 16px; }

The gap between that heading and paragraph is 24px, not 40px. This only happens vertically between block elements in normal flow; padding, borders, and horizontal margins never collapse, and neither do margins inside flex or grid containers.

The practical result: don't fight it. Use consistent spacing in one direction — for example, margin-bottom only — and the surprise disappears.

8. Units

CSS lengths come in several units. Knowing which one to use is half the skill.

UnitRelative toUse it for
pxA fixed screen pixelBorders, shadows, small details
remThe root (<html>) font size, usually 16pxFont sizes and spacing — respects the user's font settings
emThe element's own font sizeSpacing that scales with the text, e.g. button padding
%The parent's sizeWidths relative to the container
vw, vh1% of the viewport width or heightBig hero sections
chThe width of a "0"Line lengths, like max-width: 65ch
unitlessA multiplierline-height: 1.6

Many people raise their browser's default font size for readability. If you size text in px, you override their choice; sizes in rem follow it. A good habit is rem for type and spacing, px for borders, % or max-width for layout. So 1.25rem is 20px by default, but 25 px if the reader asked for bigger text.

9. Spacing the Profile Page

Update style.css with the box-model basics:

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

body {
  margin: 0;
}

header,
main,
footer {
  max-width: 48rem;
  margin: 0 auto;
  padding: 1rem;
}

section {
  margin-bottom: 2rem;
}

.card {
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}

nav ul {
  padding: 0;
}

img {
  max-width: 100%;
  height: auto;
}

input,
textarea {
  display: block;
  width: 100%;
  max-width: 28rem;
  padding: 0.5rem;
  margin-bottom: 1rem;
}

th,
td {
  padding: 0.5rem 1rem;
  text-align: left;
}

Reload and inspect a .card in DevTools to see the box diagram match the numbers.

10. Try It Yourself

  1. Read the box. Select a .card in DevTools and open the Computed tab. What are the padding, border, and total width?
  2. Break it, then fix it. Remove the box-sizing rule, give .card width: 100% and padding: 1rem. Does it overflow? Put the rule back.
  3. Make a button. Turn a link into a button using the .button class above. Change display to inline and notice what breaks.
  4. Margin collapse. Give an <h2> a margin-bottom: 40px and the next <p> a margin-top: 40px. Measure the gap in DevTools. Why 40, not 80?
  5. Test units. Change your browser's default font size (Chrome: Settings → Appearance → Font size). What changes in a page that uses rem and in one that uses px?
  6. Centered layout. Add max-width and margin: 0 auto to a page wrapper and shrink the window. When does it stop being centered?

Next, we'll make it beautiful: fonts, color, contrast, backgrounds, and a dark mode.

Buy Me a Coffee

Found this tutorial helpful? Consider buying me a coffee to support more free content!