Follow @endyourif rss Facebook LinkedIn

CSS Attribute Selectors CSS Attribute Selectors

Published on Mar 8, 2019

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:

/* 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;

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;

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.

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.

Tags: CSS | CSS

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP