Lesson 2 — Fundamentals

Selectors

Selectors determine which HTML elements a CSS rule applies to, ranging from simple tag names to precise combinations of class, id, and relationship.

Core Selector Types

The three foundational selectors target elements by tag name, class, or id. Classes can be reused across many elements; an id should match exactly one element per page.

CSS — Core selectors
p { color: #333; }              /* every <p> */
.highlight { background: yellow; } /* any element with class="highlight" */
#main-header { font-size: 2rem; }  /* the single element with id="main-header" */

Combinators

Combinators let you target elements based on their relationship to other elements, without needing to add extra classes.

  • div p — a descendant selector: any p inside a div, at any depth.
  • div > p — a child selector: only p elements that are direct children of a div.
  • h2 + p — an adjacent sibling: a p immediately after an h2.
  • h2 ~ p — a general sibling: any p that follows an h2 at the same level.

Common Mistakes

  • Using an id selector for something that will be reused on the page — ids should be unique.
  • Confusing the descendant selector (space) with the child selector (>), which target different levels of nesting.
  • Over-relying on deeply nested selectors like div div div p instead of a single, clear class.
  • Forgetting the dot (.) before a class name or the hash (#) before an id name in a selector.

Professional Tip

Favour classes over ids for styling. Classes are reusable and don't carry the higher specificity weight of ids, which makes overriding styles later much easier.

Your Turn

Style a page with a nav containing links: use a class selector to colour all nav links blue, and a child combinator to add extra spacing only to direct list items inside the nav's ul.

Mini Quiz

Which selector targets only direct children of an element, not deeper descendants?