Webistrate - Draw Your Own Conclusions

CSS3: Attribute Selectors

Posted by Jamie Munro | September 19, 2011 | Tags:


Have you ever wanted to set a custom style on all images that contain .png as their extension?  How about some custom CSS for a URL that is under SSL (perhaps add a lock image beside it?).  In CSS3, new attribute selectors have been added to allow for partial matches to attribute values.  The match can be at the start, end, or anywhere else in the string.

Attribute 1 – Start of string matching

If you wish to apply a style to all links that contain https, you would utilize the ^= attribute selector.  Here is an example of making all secure links have a different color link:

/* default link color */
a {
color: #DBDBDB;

/* only SSL link color */
a[href^=https:] {
color: #666666;

This attribute selector can also work on all sorts of other methods.  For example, what about every paragraph tag with an id that begins with title-

p[id^=title-] {
background-color: red;

Attribute 2 – End of string matching

In this example, let’s add different border colors to images that contain different extensions.  I would like all PNGs to have a black border and all JPGs should have a gray border.  This is accomplished by utilizing the $= attribute selector.

img[src$=png] {
border-color: #000000;

img[src$=jpg] {
border-color: #CCCCCC;

Attribute 3 – Partial matching anywhere in string

Using start and end matching will typically provide more accurate matching; however, sometimes you must match a particular string that potentially exists anywhere within the attribute.  As an example, if you want to ensure that all classes that contain the word “error” in it should have the text color of red and bold.

[class*=error] {
color: red;
font-weight: bold;

In the above example no specific tag is referenced, so any tag that contains the word error in its class name will have this style applied to it.  Use the above example with caution – unexpected results may occur with such a common, global replacement.


Taking advantage of the new CSS3 attribute selectors, when used properly, can help significantly reduce the amount of custom CSS required for related requirements.


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books