CSS Foundations

Lesson 2 of 6

The Box Model

Every element on a page is rendered as a rectangular box, and every box is built from the same four layers, from the inside out.

.card {
  width: 300px;
  padding: 16px;      /* space between content and border */
  border: 2px solid #333; /* the border itself */
  margin: 24px;       /* space outside the border, between this box and others */
}
LayerWhat it does
ContentThe actual text/images, sized by width/height.
PaddingTransparent space inside the border, pushes content inward.
BorderA visible (or invisible) line around the padding.
MarginTransparent space outside the border, pushes other elements away.

box-sizing

By default, width only sets the content width, padding and border are added on top, so a 300px-wide box with 16px padding and a 2px border actually takes up 336px. Most developers override this globally:

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

With border-box, width: 300px means the whole box, content, padding, and border, is 300px total, which is far more predictable when building layouts.

display: block vs. inline

  • Block elements (<div>, <p>, <h1>) take the full available width and stack vertically; width/height/margin all apply normally.
  • Inline elements (<span>, <a>) only take up as much width as their content and sit in the flow of text; vertical margin/height are ignored.
  • display: inline-block gives you the best of both, flows like text but respects width/height/margin.

TIP

When a layout looks subtly "off" by a few pixels, the box model is the first thing to check, open devtools and look at the computed padding, border, and margin for the element in question.

📝 Box Model Quiz

Passing score: 70%
  1. 1.Which box-model layer sits directly outside the border?

  2. 2.With box-sizing: border-box, the width property includes padding and border.

  3. 3.The CSS property that adds transparent space between an element's content and its border is ____.