CSS Attribute Selectors
An attribute selector chooses elements by an attribute they carry. An attribute is a setting written on an element in HTML.
Select by presence
The link carries an href attribute. The [href] selector turns its text red.
[href] {
color: red;
}Select by exact value
The value test must match the whole value. The link href is exactly # here.
a[href="#"] {
color: blue;
}Select the button by type
The button carries a type attribute with the value button. Its text turns green.
[type="button"] {
color: green;
}Example
a[href="#"] {
color: red;
}
[type="button"] {
color: blue;
}
[class="intro"] {
color: green;
}Key points
- Presence selector: brackets with an attribute name, like [href]
- Exact value selector: brackets with a name and a value, like [href="#"]
- Quotes around a simple value are optional.
- An attribute selector can join an element selector, like a[href].
- The value must match the case used in the attribute.
In this example, the first rule matches the link by its exact href value. The second rule matches the button by its type value. The third rule matches the intro paragraph by its class value. Each rule tests a different attribute.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which selector matches a link whose href is exactly #?