Attribute Selectors
Attribute selectors target elements based on their attributes and values. They're useful for styling form inputs, links with specific behaviors, and elements with data attributes.
Attribute Selector Types
Selector | Matches | Example |
|---|---|---|
[attr] | Has attribute | [disabled] |
[attr="value"] | Attribute equals value | [type="text"] |
[attr~="value"] | Attribute contains word | [class~="active"] |
[attr|="value"] | Attribute starts with value- | [lang|="en"] |
[attr^="value"] | Attribute starts with value | [href^="https"] |
[attr$="value"] | Attribute ends with value | [href$=".pdf"] |
[attr*="value"] | Attribute contains value | [src*="image"] |
CSS
/* Attribute existence */
input[required] {
border-color: red;
}
/* Exact value */
input[type="text"] {
padding: 8px;
}
/* Value substring */
a[href^="https"] {
padding-right: 20px;
background-image: url(lock-icon.png);
}
/* File extension */
a[href$=".pdf"] {
padding-right: 20px;
background-image: url(pdf-icon.png);
}
/* Contains value */
input[name*="email"] {
background-image: url(email-icon.png);
}Practical Examples
CSS
/* Form input styling */
input[type="text"] {
border: 1px solid #ccc;
}
input[type="email"] {
border: 1px solid #ccc;
}
input[required] {
border-color: red;
}
input[disabled] {
opacity: 0.5;
cursor: not-allowed;
}
/* External link indicators */
a[target="_blank"] {
padding-right: 15px;
}
a[target="_blank"]::after {
content: ' ↗';
}
/* Data attributes */
[data-tooltip] {
position: relative;
cursor: help;
}Note
Attribute selectors target elements by their attributes. Useful for form styling, link indicators, and data attributes. Very specific and powerful.
Next
Combinators: [Combinators (descendant, child, sibling)](/css/combinators).