The cascade

Type, class, and ID selectors

Select elements by type, reusable class, or unique ID and choose the least specific selector that clearly expresses your intent.

7 minute lesson

~~~

A selector describes which existing elements a rule applies to. A type selector matches every element with that name:

p { max-width: 65ch; }

A class selector expresses a reusable styling role:

.card { padding: 1rem; }

An ID selector matches the element with that document ID:

#newsletter { border-top: 1px solid; }

Classes are the normal choice for components because they can repeat and remain easy to override. Type selectors are useful for broad defaults such as prose spacing. IDs are valuable for fragment links, labels, and script hooks, but their high specificity makes them awkward styling dependencies.

Selectors do not verify intent. If you reuse .card on an element, it receives the rule regardless of its tag or content. Name classes after a stable role rather than a visual accident such as .blue-box.

You can group selectors with commas:

h1,
h2,
h3 {
  line-height: 1.1;
}

Grouping does not combine specificity; each selector is evaluated separately.

In DevTools, select an element and inspect its Matched Rules. Add the same class to a second element, then remove it from the first. This makes the selector-to-element relationship visible without changing the rule.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →