AI Workshop: learn to build apps with AI →
CSS Selectors: How to Use Basic CSS Selectors

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


A selector allows us to associate one or more declarations to one or more elements on the page.

Element Selectors

Suppose we have a p element on the page, and we want to display the words into it using the yellow color.

We can target that element using the selector p, which targets all p elements in the page:

p {
  color: yellow;
}

Every HTML tag has a corresponding selector: div, span, img, a, and so on.

If a selector matches multiple elements, all the elements in the page will be affected by the change.

Class Selectors

Classes are identified using the . symbol:

<p class="dog-name">Roger</p>
.dog-name {
  color: yellow;
}

You can repeat the same class value across multiple elements in a document.

ID Selectors

IDs are identified using the # symbol:

<p id="dog-name">Roger</p>
#dog-name {
  color: yellow;
}

Unlike classes, you can only use an ID once per document.

Combining Selectors

Targeting an Element with a Class

You can target a specific element that has a class attached:

p.dog-name {
  color: yellow;
}

This only targets p elements with the class dog-name.

Targeting Multiple Classes

You can target an element with multiple classes by combining them without spaces:

<p class="dog-name roger">Roger</p>
.dog-name.roger {
  color: yellow;
}

Grouping Selectors

You can apply the same styles to multiple selectors by separating them with a comma:

p,
.dog-name,
#main-title {
  color: yellow;
}

Descendant Selectors

You can target elements based on their position in the document tree:

p span {
  color: yellow;
}

This targets any span inside a p, at any nesting level.

Direct Child Selector

Use > to target only direct children:

p > span {
  color: yellow;
}

Adjacent Sibling Selector

Use + to target an element immediately following another:

p + span {
  color: yellow;
}

This styles a span that comes directly after a p.

Lessons in this unit:

0: Introduction
1: ▶︎ How to Use Basic CSS Selectors
2: How to Use CSS Attribute Selectors
3: How to Use CSS Pseudo-Classes
4: How to Use CSS Pseudo-Elements