Skip to the workspace
Pebellslearn by building
Simple Selectors  ›  Capstone Project

Attribute Selectors

Attribute selectors 12 minSquare-bracket selectors match elements by whether an attribute exists or by its value exactly, at its start, at its end, anywhere inside, or as a whole word, with class-level specificity.

css / Attribute Selectors

Explore each scene at your own pace.

01 · The rule

The rule

Attribute Selectors

Square-bracket selectors match elements by whether an attribute exists or by its value exactly, at its start, at its end, anywhere inside, or as a whole word, with class-level specificity.

Match attribute presence and values without confusing substring and whole-word rules.

The café adds two links to its "Visit us" section: one to an online map and one to a printable PDF menu. The owner wants a small note after external links and a different colour for the PDF. You could add classes to every link by hand, or you could let CSS read the href attribute itself.

The rule

Square brackets select by attribute: presence, exact value, or part of the value.

The new links:

<a href="https://maps.example.com/harbour">Directions</a>
<a href="/files/menu.pdf">Printable menu</a>

The main forms, all written inside [ ]:

Selector Matches when the attribute…
[href] exists at all
[href="#menu"] equals #menu exactly
[href^="https"] starts with https
[href$=".pdf"] ends with .pdf
[href*="maps"] contains maps anywhere
[class~="dish"] has dish as one whole word in a space-separated list
a[href^="#"] {
  font-weight: bold;      /* in-page links */
}

a[href$=".pdf"] {
  color: crimson;         /* downloads */
}

Attribute selectors weigh the same as a class, (0,1,0), so a[href$=".pdf"] is (0,1,1).

The exact form = compares the whole attribute value as one string. That matters for class: [class="dish"] matches the omelette's article, whose class is exactly dish, but not the lassi's, whose class is dish special. The ~= form, or simply .dish, looks for the word in the list.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.