AI Workshop: learn to build apps with AI →
CSS Basics: More selectors

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


We’ve seen the basics of selectors.

How to target a tag:

p {
  color: red;
}

How to target multiple tags:

p, a {
  color: red;
}

Let’s now see some more selectors.

You already know we can use the class and id attributes on an HTML element.

We can select elements with a class using this syntax: .class {}

Example:

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

To select elements with a specific id, we can use this syntax: #id {}

Example:

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

There is one big difference between those two selectors.

Inside an HTML document, you can repeat the same class value across multiple elements, but you can only use an id once.

Using classes you can select an element with 2 or more specific class names, something not possible using ids.

You can target an element that has 2 (or more) classes together by combining the class names separated with a dot, without spaces.

Example:

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

In the same way, you can combine a class and an id.

Example:

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

You can create a more specific selector by combining multiple items to follow the document tree structure. For example, if you have a span tag nested inside a p tag, you can target that one without applying the style to a span tag not included in a p tag:

<span> Hello! </span>
<p>
  My dog's name is:
  <span class="dog-name"> Roger </span>
</p>
p span {
  color: yellow;
}

See how we used a space between the two tokens p and span.

This works even if the element on the right is multiple levels deep.

To restrict the match to direct children only, you can use the > symbol between the two tokens:

p > span {
  color: yellow;
}

In this case, if a span is not a direct child of the p element, it won’t have the new color applied.

Direct children will have the style applied:

<p>
  <span> This is yellow </span>
  <strong>
    <span> This is not yellow </span>
  </strong>
</p>

Adjacent sibling selectors let us style an element only if preceded by a specific element. We do so using the + operator:

Example:

p + span {
  color: yellow;
}

This assigns the color yellow to a span element that immediately follows a p element:

<p>This is a paragraph</p>
<span>This is a yellow span</span>

Let’s pause with selectors for a second now.

We have more, but I don’t want to overwhelm you.

We’ll talk about some more later.

Lessons in this unit:

0: Introduction
1: Colors
2: ▶︎ More selectors
3: Cascade
4: Specificity
5: Units
6: Advanced selectors
7: Typography
8: The box model
9: The display property
10: Responsive design
11: Create a simple design
12: The CSS Guide