CSS Selectors

Target exactly the elements you want by tag, class, id, family or attribute.

Lesson 4 of 49Beginner14 min read

A selector is the "who" of a CSS rule. Good selectors let you style exactly the right elements, such as all buttons, one particular card, or only the links inside the footer, without changing the HTML.

Selectors are worth learning well because they appear everywhere. JavaScript uses the same syntax to find elements on a page, and browser testing tools use it too. Time spent here pays off long after you finish the CSS course.

The basic CSS selectors

SelectorExampleSelects
ElementpEvery <p>
Class.cardEvery element with class="card"
ID#logoThe element with id="logo"
Universal*Every element
Grouph1, h2Every h1 and every h2

Use classes for almost all your styling. They're reusable, they say what an element is for, and they're easy to override. Element selectors are best for broad defaults, such as setting the font for every paragraph.

Combinators: selecting by family relationship

SelectorExampleSelects
Descendant (space)nav aEvery a anywhere inside nav
Child (>)ul > lili elements that are direct children of ul
Next sibling (+)h2 + pThe first p straight after an h2
Later siblings (~)h2 ~ pEvery p after an h2 with the same parent

Combinators let you style elements based on where they sit in the page. A link in the navigation can look different from a link in an article, with no extra classes needed.

Combining selectors

  • p.intro selects a <p> that also has the class intro (no space).
  • .btn.primary selects elements that have both classes.
  • .card p selects paragraphs inside an element with class card (with a space).

That one space changes everything: p.intro and p .intro are completely different selectors. Reading selectors from right to left helps: .card p means "a paragraph, inside a card".

Attribute selectors

SelectorSelects
[disabled]Elements that have the attribute
[type="email"]Attribute equals a value
a[href^="https"]Value starts with
a[href$=".pdf"]Value ends with
img[alt*="dog"]Value contains

Attribute selectors are useful for form fields and links. For example, a[href$=".pdf"] can add a small PDF icon to every link that downloads a PDF.

Keep selectors short and simple

It's tempting to write long selectors like body div.main ul li a, but they're fragile. If the HTML structure changes slightly, the rule stops working. Long selectors are also harder to override. A single, well-named class such as .menu-link is easier to read and more reliable. A good rule of thumb is to keep most selectors to one or two parts.

CSS Selectors Syntax

Selector cheat sheet

p { }            /* element    */
.note { }        /* class      */
#header { }      /* id         */
nav a { }        /* descendant */
ul > li { }      /* child      */
a[target] { }    /* attribute  */

CSS Selectors Summary

  • Selectors choose which elements a rule applies to.
  • Element, class, id, universal and grouped selectors cover most needs.
  • Combinators select by relationship: descendant, child and sibling.
  • p.intro (no space) and p .intro (with a space) mean different things.
  • Prefer short, class-based selectors that are easy to read and override.

CSS Selectors Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Class, ID and element

p {
  font-family: sans-serif;
}

#title {
  color: #17a865;
}

.tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 99px;
  background: #e1e6ff;
}

.tag.sale {
  background: #ffe3d7;
}
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 3Every paragraph gets a sans-serif font.
  2. Lines 5 to 7Only the element with id="title".
  3. Lines 9 to 14Both elements with the tag class become pills.
  4. Lines 16 to 18Only elements with both tag and sale.
Example 2

Descendant vs child

Both lists are inside .menu, but only the top-level items are direct children.

.menu li {
  color: gray;
}

.menu > li {
  font-weight: bold;
  color: #15161b;
}
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 3Descendant: every li inside .menu, at any depth, turns gray.
  2. Lines 5 to 8Child: only li directly inside .menu are bold and dark. Shoes and Hats stay gray.
Example 3

Attribute selectors for links

a[href^="https"] {
  color: #7c3aed;
}

a[href$=".pdf"] {
  color: #e5484d;
  font-weight: bold;
}
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 3Links whose href starts with "https" turn purple.
  2. Lines 5 to 8Links ending in ".pdf" turn red and bold.

Common CSS Selectors Mistakes

Forgetting the dot or hash

Don't
card { padding: 20px; }
logo { width: 120px; }
Do
.card { padding: 20px; }
#logo { width: 120px; }

Without . or #, the browser looks for <card> and <logo> elements, which don't exist.

A stray space

Don't
p .highlight { background: yellow; }
/* looks for .highlight INSIDE a p */
Do
p.highlight { background: yellow; }
/* a p that HAS the class highlight */

A space means "inside". No space means "and also".

CSS Selectors in Real Projects

Selectors beyond CSS

JavaScript uses exactly the same selectors with document.querySelector(".card"). See DOM selecting. Testing tools, browser extensions and web scrapers all use selectors too, so learning them well pays off everywhere.

CSS Selectors Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Select the element with id="hero" and all elements with class="btn".

hero { height: 300px; }
btn { padding: 10px; }
Multiple choicemedium

What does article > p select?

Multiple choicemedium

Which selector targets an element with both classes btn and large?

Predict the outputhard

Which items turn red?

<h2>Title</h2>
<p>A</p>
<p>B</p>
<style> h2 + p { color: red; } </style>
Fix the bugmedium

The CSS should make only the links inside the footer white, and the .price paragraph bold. Fix the selectors.

a footer {
  color: white;
}

p .price {
  font-weight: bold;
}
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • Footer link is white
  • Header link is not white
  • Price is bold

CSS Selectors Quiz

4 questions to check what you learned.

  1. Which selector matches every element?

    • *
    • all
    • .all
    • #all
  2. What does a[href$=".pdf"] select?

    • Links containing "pdf"
    • Links starting with ".pdf"
    • All PDF files on the page
    • Links whose href ends with ".pdf"
  3. Which should you use most for styling?

    • IDs
    • Inline styles
    • Classes
    • The universal selector
  4. How many elements does .menu li style in a menu with 3 top items and 2 nested sub-items?

    • 3
    • 2
    • 1
    • 5

CSS Selectors Challenge

Style a to-do list with selectors

Without changing the HTML:

  1. Make every li inside .todo have padding: 8px
  2. Make the li with class done have text-decoration: line-through
  3. Make the checkbox inputs (input[type="checkbox"]) have margin-right: 8px
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • Every li has 8px padding
  • The done item is crossed out
  • Other items aren't crossed out
  • Checkboxes have 8px right margin