CSS [attribute] Selector
Description
The CSS [attribute] selector is a powerful way to target HTML elements based on the presence of a specific attribute within those elements. It allows you to apply styles selectively to elements that have a specified attribute, regardless of the attribute's value.
Here's a brief overview of how it works:
Syntax: To use the [attribute] selector, you enclose the attribute name within square brackets, like this:
[attribute]
.Targeting Elements: When you use this selector, it selects all HTML elements that have the specified attribute, regardless of what value that attribute holds.
Usage: This selector is useful in various scenarios, such as styling elements with specific data attributes, targeting input fields with certain attributes (e.g.,
[required]
for required form fields), or styling links with a specifictarget
attribute (e.g.,[target="_blank"]
for opening links in a new tab).
Example:
/* Style all elements with a "data-highlight" attribute */
[data-highlight] {
background-color: yellow;
color: black;
}
In the example above, any element with a "data-highlight" attribute will have a yellow background color and black text color applied to it.
The CSS [attribute] selector is a valuable tool for creating flexible and dynamic stylesheets, allowing you to target elements based on their attributes rather than specific class or ID values.
Syntax
[attribute] { css declarations; }
Example
a[target] {
color: #3366ff;
background: #ffff99;
}
Give it a Try
Click the button below to experiment with this selector.
Browser Support
The following table will show you the current browser support for the CSS [attribute]
selector.
Desktop | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
|
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Yes | Yes | Yes | Yes | Yes | Yes |