Targeting a Specific Image Type with CSS
So I’m coding up a new site from our designer and he’s set some nice quasi-polaroid photo effects: white border, box-shadow, etc. This looks great on rectangular images, of course, but not so much on other images with transparency.
One quick fix is to set the background to the same color as the border. That fixes the lonely frame problem and puts the transparent image on “card” of sorts. It’s a step in the right direction:
My old workaround was to ask our content specialist to add the class “no-border” to any image that was transparent and thus shouldn’t have the border effect. That was less than ideal, however. WordPress doesn’t make it super-easy to add classes to images, so this would put extra work on him, require new training for anyone else who touches content, and provide an extra avenue for operator error. What I really needed was a way to target the transparent images via CSS without adding anything to them in the CMS.
Today it hit me that I could use an attribute selector to find any PNG and remove the border, shadow, and background from it. Attribute selectors are good to go on IE 7+ and all real browsers. It’s a pretty safe bet that the only image with transparency would be a PNG (if for some reason you’re still using GIFs, though, just modify this code to include them) and that the normal rectangular photo images would be JPGs. Here’s the code I use to target them (of course, choose your own border / box-shadow and do your own prefixing):
img {
border: border;
background: border-color;
box-shadow: box-shadow;
}
img[src*="png"] {
border: none;
background: transparent;
box-shadow: none;
}
Now, as you can see below, the JPG photo image has the correct border / box-shadow, while the PNG displays in all its transparent, frame-less glory.
Of course, there is a possibility that someone might upload a rectangular photo formatted as PNG, but in my opinion, that’s a good opportunity to teach them about file formats. Other than education, any ideas on how to improve this snippet to cover non-transparent PNGs?