๐ŸŽ“ A1Learner
๐Ÿ”

CSS Selectors

A CSS selector is the part of a rule that chooses which elements the rule styles. A selector can use an element name, a class, or an id.

Select by element

The p selector styles every paragraph. Every paragraph on the practice page turns red.

p {
  color: red;
}

Select by class

The .intro selector styles only the intro paragraph. The demo paragraph keeps its default colour.

.intro {
  color: blue;
}

Select by id

The #demo selector styles one element only. That element is the demo paragraph.

#demo {
  color: green;
}

Example

h1 {
  color: blue;
}
.intro {
  color: red;
}
#demo {
  color: green;
}

Key points

  • Element selector: a selector that uses an element name, like p
  • Class selector: a selector with a dot, like .intro
  • Id selector: a selector with a hash sign, like #demo
  • A class can be shared by many elements.
  • An id names one element on a page.
  • The class and id attributes come from HTML.

In this example, the element selector h1 colours the heading blue. The class selector .intro colours the intro paragraph red. The id selector #demo colours the demo paragraph green. Each selector picks a different set of elements.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which selector styles only the element with the id demo?