Selectors and the Box Model

beginner20 min

Learning objectives

  • Target elements using class and ID selectors
  • Explain the CSS box model (content, padding, border, margin)
  • Apply typography and spacing rules to a page

Learn

Selecting elements

h1 {
  color: #1e293b;
}

.card {
  background: white;
}

#site-header {
  position: sticky;
}
  • Element selectors (h1) target every element of that type.
  • Class selectors (.card) target any element with class="card" — reusable across many elements.
  • ID selectors (#site-header) target exactly one element with that id — use sparingly, IDs must be unique on a page.

The box model

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

  1. Content — the text or image itself
  2. Padding — space between content and border
  3. Border — a visible (or invisible) edge
  4. Margin — space outside the border, separating it from other elements
.card {
  padding: 16px;
  border: 1px solid #e2e8f0;
  margin: 24px;
}

Getting the box model wrong is one of the most common causes of "my layout looks broken" — always check whether unexpected spacing is padding, border, or margin.

Challenge

Style the "About Me" page you built in the previous lesson: give the page a maximum width, add padding around the content, and give any card-like sections a border and rounded corners.

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