In CSS, selectors are used to target the HTML elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles we’ll run through the different types in great detail, seeing how they work.

What is a Selector?

You have met selectors already. A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.

Some code with the h1 highlighted.

In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they need to have support in browsers for them to work.

Selector lists

If you have more than one thing which uses the same CSS then the individual selectors can be combined into a selector list so that the rule is applied to all of the individual selectors. For example, if I have the same CSS for an h1 and also a class of .special, I could write this as two separate rules.

h1 {
  color: blue;
}

.special {
  color: blue;
} 

I could also combine these into a selector list, by adding a comma between them.

h1, .special {
  color: blue;
} 

White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.

h1,
.special {
  color: blue;
}