It is possible to style HTML elements that have specific attributes or attribute values.
The CSS attribute selectors provides an easy and powerful way to apply the styles on HTML elements based on the presence of a particular attribute or attribute value.
You can create an attribute selector by putting the attribute—optionally with a value—in a pair of square brackets. You can also place an element type selector before it.The following sections describe the most common attribute selectors.
The [attribute] selector is used to select elements with a specified attribute.
The following example selects all <a> elements with a target attribute:
You can use the
= operator to make an attribute selector matches any element whose attribute value is exactly equal to the given value:
The [attribute~="value"] selector is used to select elements with an attribute value containing a specified word.
The following example selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower":
You can use the
|= operator to make an attribute selector matches any element whose attribute has a hyphen-separated list of values beginning with the specified value:
The selector in the above example matches all elements that has an
lang attribute containing a value start with
en, whether or not that value is followed by a hyphen and more characters. In other words, it matches the elements with
lang attribute that has the values
en-GB, and so on but not
The [attribute^="value"] selector is used to select elements whose attribute value begins with a specified value.
The following example selects all elements with a class attribute value that begins with "top":
Similarly, you can use the
$= operator to select all elements whose attribute value ends with a specified value. It does not have to be a whole word.
The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.
The following example selects all elements with a class attribute value that contains "te":
The attribute selectors can be useful for styling forms without class or ID: