Topic 5 of 62
Attribute Selectors
Overview
Attribute selectors allow you to style HTML elements based on the presence, or the exact value, of their HTML attributes (like type, href, or data-*). This is incredibly powerful for forms and external links, allowing you to style them precisely without needing to litter your HTML with dozens of arbitrary utility classes.
Syntax
css
/* 1. Presence: Targets any element that simply has a 'disabled' attribute */
button[disabled] {
opacity: 0.5;
cursor: not-allowed;
}
/* 2. Exact Match: Targets text inputs specifically */
input[type="text"] {
border: 1px solid #ccc;
}
/* 3. Prefix Match (^=): Targets links that start with 'https' (External links) */
a[href^="https"] {
color: red;
}
/* 4. Suffix Match ($=): Targets links that end with '.pdf' */
a[href$=".pdf"] {
background-image: url('pdf-icon.png');
}
/* 5. Substring Match (*=): Targets any image where the alt text contains 'logo' */
img[alt*="logo"] {
border: 2px solid gold;
}Common Pitfalls
- Forgetting the quotes around the attribute value. While CSS permits unquoted values in some cases (like
[type=text]), it violently breaks if the value contains spaces or special characters. Always write it safely as[type="text"]. - Using attribute selectors for massive layout systems. Because browsers evaluate selectors right-to-left, checking string substrings (like
*=) across thousands of DOM nodes is mathematically slower than just checking for a simple.class.
Interview Questions
Q:
How would you write a CSS selector to target every checkbox input on the page?
A:
Using an exact attribute selector: input[type="checkbox"] { ... }.
Real-World Example
Automatically styling secure external links distinctly from internal site links.
example
css
/* Internal links (e.g., href="/about") */
a {
color: blue;
text-decoration: none;
}
/* External secure links get an icon injected using the Prefix match */
a[href^="https://"]::after {
content: " ↗";
font-size: 0.8em;
}Check Your Knowledge
Test your understanding of Attribute Selectors with these quick questions.