CSS Attribute Selectors
Attribute selectors target elements based on the presence or value of an HTML attribute, using square brackets.
Sometimes you want to style elements by something other than their tag, class, or id. Attribute selectors let you match on any attribute, such as the type of an input, the target of a link, or a custom data attribute.
Matching by Attribute and Value
The simplest form, <[attr]>, matches any element that has the attribute at all. Add a value with <[attr='value']> to match only an exact value.
Presence and exact value
<!DOCTYPE html>
<html>
<head>
<style>
/* Any element with a title attribute */
[title] {
cursor: help;
}
/* Only text inputs */
input[type='text'] {
border: 1px solid #ccc;
padding: 8px;
}
</style>
</head>
<body>
<p>Hover this <abbr title="Cascading Style Sheets">CSS</abbr> term to see the cursor change.</p>
<input type="text" placeholder="Your name">
</body>
</html>Partial Match Operators
Several operators match part of a value, which is handy for links and file types.
Styling links by their destination
<!DOCTYPE html>
<html>
<head>
<style>
/* External links */
a[href^='http'] {
color: #00643c;
}
/* PDF downloads */
a[href$='.pdf']::after {
content: ' (PDF)';
font-size: 0.85em;
}
/* Any mailto link */
a[href*='mailto'] {
text-decoration: underline dotted;
}
</style>
</head>
<body>
<a href="https://example.com">External site</a><br>
<a href="/files/report.pdf">Download report</a><br>
<a href="mailto:hello@example.com">Email us</a>
</body>
</html>Note: Add an i before the closing bracket, like [href$='.PDF' i], to make the match case-insensitive.
- Great for form controls, where type distinguishes text, email, and checkbox inputs
- Useful with data-* attributes to style components by state
- Combine with other selectors, such as input[required] or a[target='_blank']
Exercise: CSS Attribute Selectors
What does the selector input[type] match, with no value given?