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, 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.
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:
[code]
/* default link color */
a {
color: #DBDBDB;
}
/* only SSL link color */
a[href^=https:] {
color: #666666;
}
[/code]
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-
[code]
p[id^=title-] {
background-color: red;
}
[/code]
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.
[code]
img[src$=png] {
border-color: #000000;
}
img[src$=jpg] {
border-color: #CCCCCC;
}
[/code]
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.
[code]
[class*=error] {
color: red;
font-weight: bold;
}
[/code]
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.
Summary of CSS Attributes
Taking advantage of the new CSS3 attribute selectors, when used properly, can help significantly reduce the amount of custom CSS required for related requirements.