CSS Attribute Selectors
CSS Attribute Selectors: Matching Elements by Attributes
CSS attribute selectors target HTML elements based on the presence or value of their attributes—such as styling input[type="email"], highlighting external https:// links, or flagging .pdf download links without adding extra helper classes in HTML.
Seven Attribute Selector Operators
[disabled]: Matches any element carrying thedisabledattribute.[type="email"]: Exact match (=).[class~="card"]: Matches whitespace-separated word inside an attribute.[lang|="en"]: Matches"en"or"en-US","en-GB".[href^="https://"]: Prefix match (^=starts with)—great for external link icons.[href$=".pdf"]: Suffix match ($=ends with)—great for file-type badges.[href*="github"]: Substring match (*=contains anywhere).
input[type="text"],
input[type="email"],
input[type="password"] {
width: 100%;
padding: 10px 12px;
border: 1px solid #cbd5e1;
border-radius: 6px;
}
button[disabled] {
opacity: 0.5;
cursor: not-allowed;
}
a[href^="https://"]::after {
content: " ↗";
font-size: 0.85em;
}
a[href$=".pdf"]::after {
content: " (PDF)";
color: #dc2626;
font-weight: 600;
}
Case-Insensitive Matching Flag
Add an i flag before the closing bracket—like a[href$=".PDF" i]—to match .pdf, .PDF, or .Pdf regardless of uppercase filenames. Conversely, add an s flag whenever exact case sensitivity matters for custom tokens or query flags.
Common Mistakes to Avoid
- Repeating
[type="text"]styles without excludingcheckboxorradio: Writing bareinput { width: 100%; }stretches checkboxes to full width! Always filter withinput[type="text"]orinput:not([type="checkbox"]):not([type="radio"]). - Using
[class="btn"]when an element has two classes:[class="btn"]fails onclass="btn primary"because it demands an exact string match; use.btninstead. - Overusing slow wildcard
[href*="..."]on thousands of nodes: Keep attribute selectors specific (a[href$=".pdf"]) rather than*[data-*].
Frequently Asked Questions
What is the CSS specificity of an attribute selector?
An attribute selector like [type="email"] has the exact same specificity weight (0, 1, 0) as a class selector or pseudo-class.
How do I style custom data-* attributes in CSS?
Target them like any attribute: [data-status="error"] { border-color: #dc2626; }.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.