BETAThis is a new service – your feedback will help us to improve it.

CSS selectors

Consider the following HTML.

<div class="summary">
  <h1 id="emphasised">Make this text red</h1>
  <h2>Not this text</h2>
</div>
<div>
  <h1>Not this text</h1>
</div>

What CSS would we have to write to make the first <h1> element turn red, but not the second one?

Copy this HTML across to Codepen and experiment with the following CSS examples.

Tag selectors

We can target all content inside a HTML tag of a certain type with a CSS statement like:

h1 {
  color: red;
}

However, that won't work in this situation, because both <h1> elements will turn red.

Class selectors

We can also target HTML classes, such as the class summary on the first <div>, by putting a full stop before the selector.

.summary {
  color: red;
}

However, that still won't work, because both the <h1> and <h2> will turn red.

Chaining selectors

We can write chained selectors like this.

.summary h1 {
  color: red;
}

This CSS statement will do what we need. Because we used a chained selector, we are targeting all <h1> elements inside anything with a class of summary.

ID selectors

There is one other solution which will work. We can target the ID of the <h1> element we want to turn red by putting a hash (#) before the ID name.

#emphasised {
  color: red;
}
Try and write a CSS rule to change the colour of the h2 element instead.

We can style two <h1> headings differently by..

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Building webpages
  1. Your first webpage
  2. Introducing HTML
  3. HTML attributes
  4. Classes and IDs
  5. Introducing CSS
  6. CSS selectors
  7. CSS specificity
  8. Creating layouts
  9. Responsive design
  10. Get confident with HTML and CSS
  11. Turn your prototypes into webpagesP