Sub topic 4
Selecting by attribute
This chapter assumes you can write type, class, and ID selectors and know how HTML attributes work. It also assumes you have a rough idea of what specificity means. The chapter covers the attribute selector forms, their matching rules, their specificity, and the mistakes people make with them.
What an attribute selector does
An attribute selector matches an element by looking at the attributes in its start tag. It goes in square brackets and can stand alone or attach to another selector.
[disabled] { opacity: 0.6; }
a[target="_blank"] { text-decoration: underline; }The first rule matches any element that has a disabled attribute, whatever its value. The second matches only a elements whose target is exactly _blank.
Attribute selectors match attributes, not DOM properties. If a user types into <input value="">, the value attribute in the markup does not change, so [value=""] still matches. Calling setAttribute() in JavaScript does change what matches.
The seven forms
| Form | Matches when the attribute... | Example | Column | Column |
|---|---|---|---|---|
| `[attr]` | exists, with any value | `[hidden]` | ||
| `[attr="v"]` | equals `v` exactly | `[type="email"]` | ||
| `[attr~="v"]` | is a whitespace-separated list containing the word `v` | `[class~="card"]` | ||
| `[attr\ | ="v"]` | equals `v`, or starts with `v` followed by `-` | `[lang\ | ="en"]` |
| `[attr^="v"]` | starts with `v` | `[href^="https://"]` | ||
| `[attr$="v"]` | ends with `v` | `[href$=".pdf"]` | ||
| `[attr*="v"]` | contains `v` anywhere | `[href*="example"]` |
Here is a short stylesheet that uses most of them. Each rule is explained in the sections that follow.
/* Presence */
input[required] { border-color: #c00; }
/* Exact value */
input[type="email"] { font-family: monospace; }
/* Word in a list */
[data-flags~="new"] { outline: 2px solid gold; }
/* Language subtag prefix */
[lang|="en"] { quotes: "\201C" "\201D"; }
/* Substring forms */
a[href^="https://"] { color: green; }
a[href$=".pdf"]::after { content: " (PDF)"; }
a[href*="example.com"] { font-weight: bold; }Matching details that cause surprises
Exact match means the whole string
[class="card"] matches only when the entire class attribute is the string card. It does not match class="card featured". To test for one class among several, use .card or [class~="card"]. The .card form is almost always the better choice, because it is shorter and also reads better.
The `~=` form splits on whitespace
[data-flags~="new"] matches data-flags="new sale" but not data-flags="renewed". If the value you search for contains whitespace, or is empty, the selector matches nothing.
The `|=` form is for hyphenated values
[lang|="en"] matches en, en-US, and en-GB. It does not match eng, because the character after en must be a hyphen. This form exists for language codes, and you will rarely need it for anything else.
Empty values match nothing in substring forms
[href^=""], [href$=""], and [href*=""] match no elements. This matters if you build selectors by string concatenation in a script. An empty variable silently turns a broad selector into one that matches nothing.
Quoting
Quotes are optional when the value is a valid CSS identifier, such as [type=text]. They are required when the value has spaces, starts with a digit, or contains characters like /, ., or :.
a[href="/docs/intro.html"] { color: navy; }Without the quotes, that selector is invalid and the browser drops the whole rule. Always quoting is the safer habit.
Case sensitivity
Attribute names in HTML documents are case-insensitive, so [TYPE] and [type] match the same attributes. Values are case-sensitive by default, with a short list of exceptions in HTML. For example, the type attribute on input is compared without regard to case.
You can control value matching with a flag before the closing bracket:
a[href$=".pdf" i] { color: crimson; } /* matches .PDF and .Pdf */
a[href$=".pdf" s] { color: crimson; } /* forces case-sensitive */The i flag makes the comparison case-insensitive. The s flag forces case-sensitive matching, even for attributes where HTML would otherwise ignore case. The s flag is newer and has less support than i, so check your target browsers before relying on it.
Choosing a form
Specificity
An attribute selector counts in the middle column of the specificity triple, the same as a class or a pseudo-class. The value you match against makes no difference. The i and s flags add nothing either.
input { color: black; } /* (0,0,1) */
[type="text"] { color: green; } /* (0,1,0) */
input[type="text"] { color: blue; } /* (0,1,1) */
input[type="text"][required] { color: red; } /* (0,2,1) */Two things follow from this. First, [id="main"] has the specificity of a class, (0,1,0), while #main has (1,0,0). Some authors use [id="main"] deliberately to select an ID without paying the ID specificity cost. Second, an attribute selector will not beat a class selector on its own. If .btn and [type="submit"] both target a button, the one that comes later in the source wins.
.btn { background: gray; }
[type="submit"] { background: teal; } /* wins: same specificity, later */Stacking attribute selectors raises specificity quickly. Each one adds a full class-level point, which makes later overrides harder.
Combining with other selectors
Attribute selectors work with combinators, pseudo-classes, and pseudo-elements.
form > input[type="checkbox"]:checked + label { font-weight: bold; }This selects a label that directly follows a checked checkbox input that is a child of a form. Its specificity is (0,2,3): one attribute and one pseudo-class, plus form, input, and label. The combinators add nothing.
Practical uses and limits
Attribute selectors fit these cases well:
- Styling form controls by
type, such asinput[type="range"]. - Marking up external or file-type links with
^=and$=. - Hooking styles to state attributes like
[aria-expanded="true"]or[hidden]. - Using
data-*attributes as style hooks, for example[data-state="open"].
Some limits are worth knowing:
- Substring matching on
hrefis fragile.[href*="example.com"]also matcheshttps://notexample.com. - Matching on
classorstyleattributes with=breaks as soon as someone adds another class or declaration. - Selecting on
[style]is possible, but it only tells you that an inline style exists, not what it contains in any useful way. - Browsers match right to left, so a bare attribute selector such as
[data-x]is checked against every element. This rarely matters for performance, but qualify the selector with a type if you have a large document.
Common errors
- Using
=where~=was meant, so a selector stops matching when a second class or flag appears. - Leaving out quotes around a value that contains
/or., which invalidates the rule. - Expecting
[value="x"]to track what the user types. - Using
*=for a short string and matching more than intended. - Forgetting that
[id="x"]is(0,1,0)and then wondering why it loses to#x.
Exercise
A page has <a href="/files/REPORT.PDF">. Write one selector that matches every link ending in .pdf, regardless of case. What is its specificity, and does it beat a.download if both match the same link and a.download comes later in the source?
Show answer
Use a[href$=".pdf" i]. Its specificity is (0,1,1): one attribute for the class column and one type for the type column. The i flag adds nothing. a.download is also (0,1,1). The two tie, so the later rule, a.download, wins.
Exercise
Why does [data-flags~="new"] not match <p data-flags="renewed">, while [data-flags*="new"] does?
Show answer
The ~= form compares whole whitespace-separated words, and renewed is a different word from new. The *= form matches any substring, and new appears inside renewed.