CSS Essentials

This page demonstrates selectors, specificity, and the box model — the foundation of all CSS.

1. Selectors

Selectors target the HTML elements you want to style.

Common Selector Types

This paragraph has a highlighted span using a class selector.

This paragraph is targeted by an ID selector.

This external link is styled with an attribute selector

2. Specificity

When multiple rules target the same element, the one with the highest specificity wins.

This text has three competing rules. The ID selector wins (it appears red).

Specificity Rank (simplified)

  1. Inline styles (highest)
  2. ID selectors (#id)
  3. Class, attribute, and pseudo-class selectors (.class, :hover)
  4. Element and pseudo-element selectors (p, ::before)

Teaching tip: Prefer classes over IDs for styling. Save IDs for JavaScript hooks and unique page landmarks.

3. The Box Model

Every element is a box made of four parts (from inside out): content → padding → border → margin.

content-box (default)
Width = 200px content only.
Total width = 200 + 40 + 16 = 256px
border-box (recommended)
Width = 200px includes padding + border.
Much easier to reason about.

Best practice: Set box-sizing: border-box; globally (we already did this in the reset at the top of styles.css).