demosthenes.info

Independent notes on CSS, SVG, animation and front-end design.

Articles / Article

The Attribute Selector

Regular expressions For CSS

Attribute selectors are another area of CSS that have historically been underused and unappreciated, partly due to a historical lack of support in IE. However, the selectors that I am about to show you are supported in every modern browser, including IE7+.

Attribute selectors are a simple form of regular expression pattern matching for CSS, and one of the tools we can use to reduce additions to our markup, which is always a good thing; as a general rule, the more markup we can eliminate the easier our HTML and CSS becomes to create and maintain, and the more consistent our site appears.

Simple Attribute selector

Example 1:

Matches:

Example 2:

Matches:

Matches every element that uses the stated attribute, no matter what the value of the attribute might be. I don’t find this version of the selector terribly useful, as most elements will feature shared uses of an attribute. What comes next gets more interesting:

Attribute value selector

Matches:

(Note the lack of spaces in the selector)

Very useful for selecting form elements, among other purposes. However, the exact value of the attribute must be known. That is not the case with the next set of selectors.

Separated attribute value selector

Matches:

Whereas the standard attribute selector looks for an exact matching value, the ~= CSS attribute selector will match a value from a space-separated list.

CSS3 adds three variations to the attribute selector:

Attribute “starts with” value selector

Matches:

Matches an attribute value that starts with a set of characters.

Attribute “ends with” value selector

Matches:

Also matches:

Attribute “includes” value selector

Matches: