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.
The links
The page now has four links:
#menu,#visit, the maps URL and/files/menu.pdf.
Drills
Answer fast — trust the rule.
Which links does a[href^="#"] match on the café page?
How many articles does [class="dish"] match?
Which selector matches both dish articles by looking for the word in the class list?
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.
