CSS Attribute Selectors CSS Attribute Selectors

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.

Published on Mar 8, 2019

Tags: The Ultimate CSS Tutorial for Beginner Programmers

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.