CSS [attribute] Selector

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

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:

  1. Syntax: To use the [attribute] selector, you enclose the attribute name within square brackets, like this: [attribute].

  2. Targeting Elements: When you use this selector, it selects all HTML elements that have the specified attribute, regardless of what value that attribute holds.

  3. 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 specific target 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.

Give it a Try!

Browser Support

The following table will show you the current browser support for the CSS [attribute] selector.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes