Lesson 4 +10 XP

CSS Selectors

CSS Selectors

A selector tells the browser WHICH elements to style. Let's learn the basic crew that works together on every page.

1. The element selector (tag name)

Styles every element with that tag name.

p {
  color: red;
}

This turns ALL paragraphs red.

2. The id selector (a #)

Styles ONE specific element by its id. IDs must be unique!

#header {
  color: white;
  background: black;
}

This styles the element with id="header".

3. The class selector (a .)

Styles every element with that class name. Classes can be reused as much as you want!

.center {
  text-align: center;
}

This styles every element with class="center".

4. The universal selector (*)

Styles EVERYTHING on the page.

* {
  box-sizing: border-box;
}

Powerful, use it carefully.

5. Grouping selectors

Style several selectors at once with a comma.

h1, h2, h3 {
  font-family: sans-serif;
}

Same result as writing three separate rules! Less typing, same style.

Specificity quick peek

Each selector type carries "weight":

  • id (100) beats class (10) beats element (1), so an id-style usually wins. The full hierarchy comes in the Specificity lesson.

TL;DR

  • p element: all elements of that tag.
  • #id is a unique element.
  • .class any one with that class.
  • *: every element.
  • h1, h2: group them with comma.
  • Specificity later decides winners.