CSS Attribute Selectors

Style HTML Elements With Specific Attributes

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.

CSS [attribute] Selector

The [attribute] selector is used to select elements with a specified attribute.

The following example selects all <a> elements with a target attribute:

Example -

CSS [attribute="value"] Selector

You can use the = operator to make an attribute selector matches any element whose attribute value is exactly equal to the given value:

Example -

CSS [attribute~="value"] Selector

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":

Example -

CSS [attribute|="value"] Selector

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:

Example -

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, en-US, en-GB, and so on but not US-en, GB-en.

CSS [attribute^="value"] Selector

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":

Example -

CSS [attribute$="value"] Selector

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.

Example -

CSS [attribute*="value"] Selector

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":

Example -

Styling Forms with Attribute Selectors

The attribute selectors can be useful for styling forms without class or ID:

Example -