Match elements by their attributes and group selectors.
An attribute selector selects elements by an HTML attribute. Square brackets can check that an attribute exists or compare its value.
Consider two links:
a[title] {
color: green;
}Only the first link matches. Read a[title] in two parts:
a limits the match to links.[title] keeps the links that have a title attribute.The attribute's value can be empty or any other text; this selector checks presence, not a particular value.
Use = to match an exact attribute value:
a[href="docs.html"] {
font-weight: bold;
}This matches href="docs.html", but not href="docs.html#delivery". The second value contains extra text, so it is not an exact match.
Complete the selector before reading the explanation:
a[href__="docs.html"] {
font-weight: bold;
}The missing operator is =. Start by asking whether the whole value must match; then choose the operator that expresses that relationship.
When an exact match is too narrow, choose the operator by the kind of match you need:
| Selector | Matches when the value… |
|---|---|
~= | Contains value as a whole word in a space-separated list. |
| ` | =` |
^= | Starts with value. |
$= | Ends with value. |
*= | Contains value anywhere. |
These examples show both the match and the reason it works:
/* The whole word note is present in the class list. */
[class~="note"] {
background-color: yellow;
}
/* en-GB begins with en followed by a hyphen. */
[lang|="en"] {
color: green;
}
/* The URL starts with https:// and ends with .pdf. */
[href^="https://"][href$=".pdf"] {
font-weight: bold;
}The first rule matches class="note featured" but not class="notebook": ~= checks words, while *= would allow a match inside a larger word. The language rule matches en and en-GB, but not english. The last rule combines two conditions on the same link, so its href must start with https:// and end with .pdf.
For a class name, .note expresses the same whole-class match as [class~="note"]. Use the attribute form when the attribute itself, or the kind of value match, is what matters.
A selector list lets different matches share declarations:
a[href$=".pdf"],
a[title] {
font-weight: bold;
}The first selector matches the first two links. The second matches the first and third. The comma means or, so all three links become bold because each matches at least one selector.
Without a comma, conditions are joined on one element:
a[title][href$=".pdf"] {
color: purple;
}Only the first link matches this rule because it has both the title attribute and an href ending in .pdf.
Before writing a selector, name the relationship you need:
[title].[href="docs.html"].[class~="note"].^=, $=, or *=.Try it yourself
HTML + CSS