CSS — Page Layout, Box Model & Responsive Design

intermediate25 min

Learning objectives

  • Apply the CSS box model to control layout
  • Build responsive layouts using CSS media queries and layout tools

Learn

C1 — Controlling layout, and making it work on every screen

The box model

Every HTML element is a box made of four layers, from the inside out:

.card {
  padding: 16px;       /* space inside the box, around the content */
  border: 1px solid #cbd5e1;
  margin: 24px;         /* space outside the box, between it and its neighbours */
}

Content → padding → border → margin. An element's actual on-page size is its content plus padding plus border — margin sits outside that and only affects spacing to neighbouring elements. Getting padding and margin confused is one of the most common CSS mistakes: padding pushes content away from its own edge; margin pushes the whole box away from other boxes.

It doesn't just need to work on your screen

It's tempting to build and test only on your own laptop and assume that's "done" — but a real visitor could be on a phone, a tablet, or a much smaller or larger monitor than yours. A layout that looks perfect at your exact screen width can genuinely break — overlapping text, a menu running off the edge — at a different one. Checking only your own device is not the same as checking the site actually works.

Media queries

nav {
  display: flex;
  gap: 16px;
}

@media (max-width: 600px) {
  nav {
    flex-direction: column;
  }
}

A media query applies CSS rules only when a condition is true — here, only when the browser window is 600px wide or narrower, which switches the navigation from a horizontal row to a stacked column so it still fits on a phone screen.

Task

Take a page you've already built. Use your browser's developer tools to resize the viewport to at least three widths (e.g. 375px, 768px, 1200px) and note anywhere the layout breaks. Add a media query that fixes the worst problem at the smallest width, then re-check all three widths again to confirm nothing else broke.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab
Log in to track this lesson on your progress dashboard.
Log in