BeginnerLesson 2 of 305 min read

CSS selectors: elements, classes, ids and combinators

Learn how to point at exactly the right elements with element, class, id, descendant and attribute selectors.

In this lesson you will

  • Select by element, class and id
  • Group selectors
  • Target elements by location
  • Choose clear, short selectors

About 13 minutes

Pointing at the right thing

Imagine you are a teacher with thirty students. If you say “stand up”, everyone stands. If you say “all the students in the red jackets, stand up”, fewer do. If you say “Maria, stand up”, exactly one does. Selectors work the same way. They are how you tell the browser who should receive the styles, from everything on the page down to a single element.

Element selectors

The simplest selector is the name of an HTML tag. It targets every element of that type.

p { color: #3B3858; }
h2 { color: #5A28C8; }

Class selectors

Classes are the workhorse of CSS. In HTML you give elements a class, and in CSS you select it with a dot.

<p class="note">Remember to save.</p>
<p>A normal paragraph.</p>
<p class="note">Back up your files.</p>
.note {
  background: #F1EDFE;
  padding: 10px;
}

Both paragraphs with the class get the look, and the plain paragraph does not. A class can be used on as many elements as you like, and an element can have several classes separated by spaces.

Id selectors

An id selects a single element and uses a hash sign. In practice most developers use classes for styling and keep ids for in-page links and scripts, because ids are less flexible.

#contact { border: 2px solid #5A28C8; }

Style only the paragraphs with the class special by giving them a light yellow background. Do not style the plain paragraph.

<style>
  /* write your rule here */
</style>
<p>A plain paragraph.</p>
<p class="special">A special paragraph.</p>
<p class="special">Another special one.</p>

A class selector starts with a dot: .special { background: … }

<style>
  .special { background: #FFF6BF; padding: 6px; }
</style>
<p>A plain paragraph.</p>
<p class="special">A special paragraph.</p>
<p class="special">Another special one.</p>

Grouping and combining

Separate selectors with commas to give them the same rule, which saves repeating yourself.

h1, h2, h3 {
  font-family: Georgia, serif;
  color: #14112E;
}

Descendant selectors

A space between two selectors means “inside”. This is how you style something only when it lives within something else.

/* links inside the navigation only */
nav a { color: white; }

/* paragraphs inside an article */
article p { line-height: 1.7; }

The links in your footer are untouched by the first rule. The selector reads from right to left: find every a that has a nav above it.

Child and sibling selectors

  • ul > li selects only direct children. A list item inside a nested list is not matched.
  • h2 + p selects a paragraph that comes immediately after an h2. It is useful for lead paragraphs.
  • h2 ~ p selects all paragraphs that follow an h2 at the same level.

Attribute selectors

a[target="_blank"] { color: #D63384; }
input[type="email"] { border-color: #5A28C8; }

Square brackets select elements by one of their attributes. They are handy for form inputs, links that open new tabs, and anything with a data- attribute.

The universal selector

* { box-sizing: border-box; }

The star matches every element. It is common in a small reset at the top of a stylesheet, and you will meet it again in the box model lesson.

Choosing the right selector

  • Reach for a class when you want a reusable look.
  • Use an element selector for broad defaults such as body text and headings.
  • Use a descendant selector to limit a rule to one area, such as the navigation.
  • Keep selectors short. .card-title is better than div.container section article h3, which breaks the moment you reorganise the HTML.
Common mistake

Forgetting the dot. note { ... } looks for an element called note, which does not exist. .note { ... } looks for the class. It is a very common slip.

Make only the links inside the nav bold and red. The link in the paragraph must stay as it is.

<style>
  /* write your rule here */
</style>
<nav><a href="#">Home</a> <a href="#">About</a></nav>
<p>Read <a href="#">more here</a>.</p>

Use a descendant selector: nav a { … }

<style>
  nav a { color: red; font-weight: 700; }
</style>
<nav><a href="#">Home</a> <a href="#">About</a></nav>
<p>Read <a href="#">more here</a>.</p>

Pseudo-classes: a first look

You will meet pseudo-classes properly in lesson 9, but one belongs here because it is a selector too. A pseudo-class is a keyword added to a selector with a colon, and it matches an element only in a certain state or position. The most familiar example is a:hover, which applies only while the pointer is over a link. Others pick elements by their place in a list: li:first-child is the first item and li:last-child is the last.

li:first-child { font-weight: 700; }
a:hover { text-decoration: underline; }
input:focus { border-color: #5A28C8; }

Reading a selector aloud

A useful trick for debugging is to read a selector out loud, right to left, in plain words. Take nav ul li a:hover. Read it backwards: “a link, when hovered, inside a list item, inside a list, inside a nav.” If that sentence does not describe the element you wanted, the selector is wrong. If it does but is wordy, shorten it by giving that link a class.

A mini exercise in thinking

Suppose a page has a nav, a main article with several paragraphs, and a footer with links. Write down, in words, which selector you would use for each of these: the nav links only, every paragraph in the article, the first paragraph in the article, and links that open in a new tab. Compare with these answers: nav a, article p, article p:first-child and a[target="_blank"]. If you chose similar ones, you already think like a CSS developer.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which selector targets elements with class="card"?

  1. card
  2. .card
  3. #card
  4. *card

A dot selects a class.

What does nav a select?

  1. Every nav and every link
  2. Links inside a nav
  3. Navs inside a link
  4. Only the first link

A space means descendant, so links located inside a nav.

Which symbol selects an id?

  1. Dot
  2. Hash
  3. Star
  4. Plus

A hash sign selects an id.

What does h1, h2, h3 { ... } do?

  1. Selects h1 inside h2
  2. Applies one rule to all three
  3. Is invalid
  4. Selects only h3

Commas group selectors to share one rule.

Why are short selectors preferred?

  1. They look nicer
  2. They keep working when the HTML changes
  3. Browsers require it
  4. They are case sensitive

Long location-based selectors break easily.

Summary

  • Elements, classes and ids are the core selectors.
  • Commas group selectors and spaces mean inside.
  • Attribute selectors use square brackets.
  • Short, class-based selectors last longest.

Next lesson

Next: colours, the fastest way to change a page.

Questions

Class or id for styling?

Mostly classes. They are reusable and easier to override. Ids are best left for links and scripts.

Can an element have both a class and an id?

Yes. It can have one id and any number of classes.

Are selectors case sensitive?

Element names are not, but class and id names are. Keep them lower case with hyphens.

Progress is saved in this browser.