Attribute Selectors Explained
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What Attribute Selectors Do
Attribute selectors match elements based on the presence or value of an HTML attribute, using square brackets. They are especially useful for styling form elements and links without adding extra classes.
Presence and Exact Match
/* Any element that has a title attribute at all */
[title] {
cursor: help;
}
/* Exact value match */
input[type="checkbox"] {
width: 18px;
height: 18px;
}Partial Value Matching
| Syntax | Matches when the attribute value... |
|---|---|
[href^="https"] | starts with "https" |
[href$=".pdf"] | ends with ".pdf" |
[class*="btn"] | contains "btn" anywhere |
[lang|="en"] | equals "en" or starts with "en-" |
[class~="active"] | contains "active" as one whole word in a space-separated list |
A Practical Example
a[href$=".pdf"] {
padding-right: 20px;
background: url("/icons/pdf.svg") no-repeat right center;
}This automatically adds a small PDF icon to any link ending in .pdf, without needing to add a class to every single link in the content.
Case Sensitivity
Attribute value matching is case-sensitive by default. Adding an i before the closing bracket makes the comparison case-insensitive, which is useful for attributes like file extensions that might be typed in different cases.
a[href$=".PDF" i] {
color: red;
}