Login | Contact Us | Site Map | Resources

Advanced CSS

Home > CSS Tutorial > CSS Attribute Selectors

CSS Attribute Selectors

Most HTML elements support attributes, which can be used as CSS selectors by defining the attribute in braces [].

The most basic example of an attribute selector is:

[href] { color: teal; }

This example basically colors the text of all elements containing the "href" attribute. A more specific example will also name the element selector:

a[href] { color: teal; }

There are other ways to style elements, so what's the point? The point is that attribute selectors allow you to play with the value of the attribute to produce unique results. Consider the following:

a[href=http://www.phpforkids.com/] { color: teal; }

Now the style is only applied if the anchor element <a> contains an "href" attribute with the value of "http://www.phpforkids.com/".

Identifying the type of a document that is being linked to, and adding an icon next to that link, is one of the most common uses of attribute selectors.

a[href$=".pdf"] {
  padding-left: 20px;
  background: url('images/examples/pdf.gif') no-repeat left center;
}

Now, using "$=", we have declared that any href attribute that contains a value of ".pdf" should have an icon that identifies the linked document as a PDF file. The result is:

CSS Cheat Sheet

Now you can put some attribute selectors together and come up with your own unique styles.