Attribute Selectors in CSS

HTML elements can have attributes. For example, an A element can have an HREF attribute. An IMG element can have a TITLE attribute. Using attribute selectors in CSS provides an additional way to hang styles on very specific elements.

An attribute selector will target a specific element if the selector matches the element or if some specified attribute condition is met. Attribute selector values are given in square brackets, [like this]. If you write an attribute selector rule where the selector matches the element, it might look like this:

img [title] {
some rules here;

This selector targets any IMG element with a TITLE attribute. It doesn’t matter what the content of that title attribute is, it only matters that the element has a title attribute.

You can get more specific than that with an attribute selector, using the syntax [att=val]. With this syntax, the attribute targeted must have a specific value. Suppose, for example, that you want to create a style for images that have the exact TITLE attribute “mybunny.” Now the TITLE attribute alone is not enough, the VALUE must match exactly as well.

img [title=mybunny] {
some rules here;

Another type of attribute selector uses a tilde-equals sign combination like this [att~=val]. With this selector, you can match any element that has a particular value among a list of space separated values. For example suppose you have an h3 element on your page with a space separated list of class attributes including bulletin and warning, like this:

<h3 class="bulletin warning">

This CSS attribute selector

some rules here;

would target the h3 element with the space separated list of attributes. It only has to match one of the items in the list.

The final type of attribute selector uses the syntax |= to match hyphenated elements. This most often is used in rules targeting specific language declarations, where you might have hyphenated attributes in an HTML element such as en-US or en-GB. An example selector is:

body [lang|="en"]{
some rules here;

That rule would match any LANG attribute that had “en” among a hyphen separated list of languages.

Technorati Tags: ,

5 thoughts on “Attribute Selectors in CSS”

  1. A good point, Dave. I did a similar piece on attribute selectors at eHow and included that info there, but overlooked including it here. Appreciate the input.

Leave a Reply