Attribute Selectors, In Depth

Substring matching, the case-insensitive i flag, and language subtag matching with the ~= and |= operators.

Basic attribute selectors match presence and exact value. The full set is richer, and once it clicks you'll style things by data attribute and never look back.

SelectorMatches when the value…
[attr]exists at all
[attr="x"]equals exactly x
[attr^="x"]starts with x
[attr$="x"]ends with x
[attr*="x"]contains x anywhere
[attr~="x"]is a whitespace-separated list containing the whole word x
[attr|="x"]equals x or starts with x- (great for lang)

The case flag

Add a trailing i to match case-insensitively (or s to force case-sensitive): [href$=".PDF" i] catches .pdf, .Pdf, and .PDF alike.

These pair beautifully with data-* attributes to build state-driven styling without a single extra class.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer uses [lang|='en'] to target all English-language variants (en, en-US, en-GB) with a single selector.
  • A developer uses [class~='icon'] to match elements that have 'icon' as one word in a space-separated class list.
  • A designer uses [href$='.pdf' i] with the case-insensitive flag to catch both .PDF and .pdf download links.

More examples

Substring matching operators

Demonstrates the three substring match operators β€” ^= (starts-with), $= (ends-with), *= (contains) β€” on href values.

Example Β· css
[href^='https']  { color: green; }  /* starts with */
[href$='.pdf']   { font-weight: bold; }  /* ends with */
[href*='example'] { text-decoration: underline; }  /* contains */

Language subtag matching with |=

Uses |= to match lang attributes that equal 'en' or begin with 'en-', catching en, en-US, and en-GB together.

Example Β· css
:lang(en), [lang|='en'] {
  quotes: '\201C' '\201D';
  font-family: 'Times New Roman', serif;
}
[lang|='fr'] {
  quotes: '\00AB' '\00BB';
}

Case-insensitive flag with i

The i flag after the attribute value makes the match case-insensitive, catching all capitalisation variants of .pdf.

Example Β· css
/* Matches .PDF, .Pdf, .pdf without extra rules */
a[href$='.pdf' i]::after,
a[href$='.PDF' i]::after {
  content: ' ↓PDF';
  color: #c0392b;
  font-size: 0.8em;
}

Discussion

  • Be the first to comment on this lesson.
Attribute Selectors, In Depth β€” CSS | SoundsCode