Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Attribute Selectors

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.

The shortcut

Say the operator as a word: = "is exactly", ^= "starts with", $= "ends with", *= "contains", ~= "has the word". Then read the value against it.

Matching links on the café pageStep 1 of 4
  1. The links

    The page now has four links: #menu, #visit, the maps URL and /files/menu.pdf.

Drills

Answer fast — trust the rule.

quick drill

Which links does a[href^="#"] match on the café page?

quick drill

How many articles does [class="dish"] match?

quick drill

Which selector matches both dish articles by looking for the word in the class list?

quick drill

What is the specificity of a[href$=".pdf"]?

Remember

  • [attr], =, ^=, $=, *=, ~=: exists, exactly, starts, ends, contains, has the word.
  • An attribute selector weighs the same as a class.
  • = compares the whole value, so [class="dish"] misses multi-class elements.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLet the href decide

The café wants in-page links bold, links to other websites in teal, and PDF links in crimson. Write attribute selectors for the three groups and explain what each operator means.