Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Attribute selectors for image styles

Posted on by Clive Walker in CSS Web Design

I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.

I have been reading several articles recently, and reminding myself, about attribute selectors. In case you’re wondering, attribute selectors in your style sheet allow you to style an element based on an attribute and value. This means that you can set-up style rules without the need to add class names to your (X)HTML. Cool! For example, you could style all external links by using a selector that targets the href attribute and matches any href value beginning with “http”.

Previously: CSS attribute selectors – clever styling

Styling images is another area where there is scope for using attribute selectors. Andy Clarke, following a clever idea by Craig Cook, describes image management, naming and attribute selectors. For example, you can style an image based on its src attribute. Think about it. This enables you to style an image based on its name or part of its name, its file extension, and/or where it is stored. For example, some of your images might be stored in a folder called thumbnails and you could use a style rule in your CSS to style these differently to images in another folder with a different name. As Andy explains, a bit like this:

img[src*="thumbnails"] {
/* Styles go here */ }

This will apply the styles to all images in any folder that has “thumbnails’ as part of its name. This is potentially very useful if your client has a problem applying image styles through a content management system or web page editing software. Simply set-up folders for the client to upload to and the styles will be applied automatically!

In fact, why use class styles for images in your (X)HTML at all when you can style an image based exactly on its name?! This may sound superficially attractive but I am not sure that you would want to be too specific since this might prove to be fairly inflexible (and a carefully considered image naming convention or guide might be required). Still, no reason not to consider this in some cases.

I think the use of attribute selectors for styling images is pretty smart and I hope to use this myself. I’m always looking for ways to streamline my code and make my CSS more efficient. I don’t always succeed but that’s another story!

Support: Browser support for attribute selectors is pretty good. Most browsers (but not IE6) support them. Further reading: Andy Budd’s 24 Ways article about the use of attribute selectors to block ads

Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Comments are OFF for this post.

© 2024 Clive Walker