Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

CSS Selectors

Learn how CSS selectors match elements so you can apply styles to exactly the parts of a document you intend to target.

Levels: Beginner ~10 min read

Basic

What a selector does

A CSS selector is a pattern that matches elements in a document. The selector identifies the elements a style rule applies to; declarations then specify what should change about their presentation.

css
1
2
3
p {
  color: rebeccapurple;
}

In this rule, p is the selector. It matches paragraph elements, while the declaration block contains the styling to apply to those matches.

Type selectors

A type selector matches elements by their element name. It is useful when the same presentation should apply to every element of that type.

css
1
2
3
4
5
6
7
h1 {
  margin-block-end: 1rem;
}

p {
  line-height: 1.6;
}

Class selectors

A class selector begins with a period followed by a class name. It lets the author target elements that share a class without requiring those elements to have the same element name.

css
1
2
3
4
.notice {
  border: 1px solid currentColor;
  padding: 1rem;
}

The class name is part of the selector syntax; the class itself is supplied by the document being styled, for example with an HTML class attribute.

ID selectors

An ID selector begins with a number sign followed by an identifier. It matches the element whose ID is the selected value.

css
1
2
3
#main-title {
  font-size: 2rem;
}

Combining selectors comes later

Type, class, and ID selectors are only the beginning. CSS also provides combinators, attribute selectors, pseudo-classes, pseudo-elements, and selector lists for expressing more precise relationships and conditions.

Was this page helpful?

Mark this learning resource complete to track your learning progress.