CSS Attr Selectors
Attribute selectors match elements based on their attributes or attribute values — perfect for styling form inputs, language-specific text, or anything carrying a data-* hint.
All the forms
| Selector | Matches |
|---|---|
[disabled] | Any element with a disabled attribute (any value). |
[type="email"] | Element whose type equals exactly "email". |
[href^="https"] | Attribute that starts with "https". |
[href$=".pdf"] | Attribute that ends with ".pdf". |
[class*="icon-"] | Attribute that contains the substring "icon-". |
[lang|="en"] | lang equals "en" or starts with "en-" (hyphen-prefix). |
[data-state~="open"] | Space-separated value list contains "open". |
Useful in real life
CSS
/* External links get a small arrow */
a[href^="http"]::after { content: " ↗"; color: #04AA6D; }
/* PDF links get a tag */
a[href$=".pdf"]::after { content: " [PDF]"; font-size: 0.85em; }
/* Disabled buttons fade */
button[disabled] { opacity: 0.5; cursor: not-allowed; }
/* Required form inputs get a red asterisk on the label */
label:has(+ input[required])::after { content: " *"; color: #E44D26; }
Tip: Attribute selectors have class-level specificity (0,0,1,0). Combine them with
[type] to style form controls without adding extra classes.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Attr Selectors</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Style every link whose href ends with ".pdf".
a[href
=".pdf"] { font-weight: bold; }
A single character meaning "ends with".
Discussion
Loading…