HTML Sample
<ul> <li><a href="#top">TOP</a></li> <li><a href="https://developer.mozilla.org">mozilla</a></li> <li><a href="https://example.com">example</a></li> <li><a href="https://www.yahoo.co.jp">yahoo</a></li></ul>Basic Attribute Selectors
/* Prefix match: starts with "#" */a[href^="#"] { color: fuchsia;}
/* Suffix match: ends with ".org" */a[href$=".org"] { color: orange;}
/* Substring match: contains "example" */a[href*="example"] { color: red;}
/* Combined condition: starts with "https" and ends with ".jp" */a[href^="https"][href$=".jp"] { color: green;}Selector Reference
| Selector | Meaning |
|---|---|
[attr] | Attribute exists |
[attr="value"] | Exact match with value |
[attr^="value"] | Starts with value |
[attr$="value"] | Ends with value |
[attr*="value"] | Contains value |
Case-Insensitive Matching (i flag)
Appending i makes the match case-insensitive.
/* Matches both ".pdf" and ".PDF" */a[href$=".pdf" i]::after { content: " (PDF)";}Combining with :not()
/* Target only external links (http/https) */a[href^="http"]::after { content: " ↗";}
/* Exclude in-page links (#) */a[href^="http"]:not([href*="example.com"])::after { content: " ↗";}Practical Examples: File Type Icons
/* Add a label to PDF links */a[href$=".pdf" i]::after { content: " [PDF]"; font-size: 0.75em; color: #c00;}
/* Add an arrow icon to external links */a[href^="https://"]:not([href^="https://example.com"])::after { content: " ↗";}
/* No style for anchor links */a[href^="#"] { text-decoration: none;}Specificity
The specificity of an attribute selector is the same as a class selector: (0, 1, 0).
a[href^="#"] { } /* (0, 1, 0) — equivalent to a class */a.internal { } /* (0, 1, 1) — class + element wins */Practical Note
This snippet fits well when I do not want to rewrite the same operation or check around css, selector, html over and over. Keeping it as a small helper makes the caller easier to read because the intent stays in the foreground.
If the branches and preconditions start growing, it is usually better not to force everything into one snippet. Splitting the steps and helper responsibilities is easier to maintain.
hsb.horse