CSS3
CSS3

Selectors

A selector is how CSS chooses WHICH elements a rule applies to everything before the curly braces { }. An element selector, like p, targets every single <p> tag on the page, with no exceptions. A class selector starts with a dot, like .card, and targets every element that has class="card" because the same class can be reused on as many elements as you want, classes are by far the most common selector in real projects. An id selector starts with a hash, like #header, and should only ever match ONE element on the entire page, since ids must be unique. Selectors can also be combined for precision: .card p targets only <p> tags that live INSIDE an element with class="card", leaving every other paragraph on the page completely untouched. This kind of targeting is what lets you style the same tag differently depending on where it appears.

Why this matters

  • ·Classes can be reused on many elements; ids are unique per page for one-off targeting
  • ·Combining selectors (e.g. .card p) targets nested elements precisely without extra HTML
  • ·Element selectors let you set sensible defaults for every tag of a type at once

Common mistakes

  • ·Overusing #id selectors makes CSS hard to override later, since ids carry very high priority
  • ·Forgetting the dot (.) before a class name, or the hash (#) before an id, means it won't match anything
  • ·Extremely long, over-specific selector chains become fragile and hard to maintain
Your code
Live preview

Frequently asked questions

Only when something is truly unique on the page (like a single page header) for anything reused, use a class instead.

Practice questions

Question 1

Create a class called .warning that makes text red and bold, and apply it to a paragraph.

Your code
Live preview

Question 2

Style only the paragraphs inside a div with class .card, without affecting paragraphs outside it.

Your code
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 10

Which symbol starts a class selector?