Selectors: Picking What to Style

Element, class, and id selectors

7 min read

Every CSS rule starts with a choice: which part of the page do you want to style? Selectors are how you make that choice. In this lesson you will meet the three selectors you will use most: element, class, and id.

Element selectors

You have already seen this one. An element selector is just the tag name, and it styles every element of that kind on the page:

p {
  color: darkslategray;
}

This turns every paragraph dark gray. Element selectors are great for setting the general look of your site: all paragraphs, all headings, all links. But sometimes you only want to style some paragraphs, not all of them. That is where classes come in.

Class selectors

A class is a label you attach to an HTML element yourself. First, add a class attribute in your HTML:

<p class="warning">Do not feed the seagulls.</p>

Then, in your CSS, select it with a dot followed by the class name:

.warning {
  color: firebrick;
  font-weight: bold;
}

The dot is the important part. .warning means "anything with the class warning". Without the dot, the browser would look for a tag called warning, which does not exist. The superpower of classes is reuse: you can put class="warning" on as many elements as you like, on any page, and they all get the same style, which is why classes are the workhorse of CSS.

Id selectors

An id is like a class, but it is meant to be unique: only one element on the page should have a given id. In HTML you write id="site-header", and in CSS you select it with a hash symbol:

#site-header {
  background-color: navy;
}

Ids are useful for one-of-a-kind parts of a page, like the main header or a signup form. But because they cannot be reused, most developers reach for classes first and save ids for special cases.

Styling several things at once

If you want the same style on several selectors, list them separated by commas:

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

Quick memory trick: a dot looks like a small tag you can stick on many things, so .class is reusable. A hash looks like a serial number, so #id is one of a kind.

Quick check

Q1 Your HTML has &lt;p class="note"&gt;. Which CSS selector targets it?

Q2 How many elements on a page should share the same id?

Want to save your progress? It's free.

Create a free account