CSS Attribute Selector

The CSS attribute selector selects HTML elements based on the presence of a specified attribute. It is written with the attribute name inside square brackets and matches elements that have that attribute, regardless of its value.

Syntax

An attribute selector that tests for the presence of an attribute is written with the attribute name inside square brackets:

[attribute] {
  property: value;
}

For example, the following selector matches every element that has a title attribute:

[title] {
  color: #0088cc;
}

How the Attribute Selector Works

The basic attribute selector matches an element when the specified attribute is present. The value of the attribute does not affect whether the element matches.

[data-info] {
  background-color: #d8f1fc;
}

The selector [data-info] matches each of the following elements because both have a data-info attribute:

<p data-info="important">Important information</p>
<div data-info="example">Example content</div>

An element without the data-info attribute does not match the selector.

Selecting Attributes with Values

CSS provides several attribute selector forms for matching an attribute according to its value. These selectors use operators inside the square brackets.

Selector Matches
[attr="value"] An attribute whose value exactly matches value.
[attr~="value"] An attribute containing value in a whitespace-separated list of words.
[attr|="value"] An attribute whose value is value or begins with value-.
[attr^="value"] An attribute whose value begins with value.
[attr$="value"] An attribute whose value ends with value.
[attr*="value"] An attribute whose value contains value.

Each of these forms is covered separately in the CSS Selector Reference.

Combining with Other Selectors

An attribute selector can be combined with a type selector to restrict the match to a particular HTML element.

input[required] {
  border-color: #0088cc;
}

This selector matches <input> elements that have the required attribute.

Attribute selectors can also be combined with classes, IDs, pseudo-classes, and other selectors.

.field[required] {
  font-weight: 600;
}
a[target]:hover {
  text-decoration: underline;
}

Specificity

An attribute selector contributes 0-1-0 to a selector's specificity. It has the same specificity weight as a class selector or pseudo-class.

Selector Specificity
[title] 0-1-0
input[required] 0-1-1
.field[required] 0-2-0
#form input[required] 1-1-1

Attribute Selector Example

The following example uses [data-info] to style elements that have a data-info attribute. The final paragraph does not have the attribute and is not affected by the rule.

[data-info] {
  background-color: #d8f1fc;
  color: #0088cc;
  font-weight: 600;
}

Play in Editor

CSS provides several attribute selectors for matching elements according to attribute values:

Specifications

The attribute selector is defined in the Selectors Level 4 specification.