Select Page

The Problem

I recently encountered an issue on one of our work websites that had the whole creative team stumped. We had a WordPress site that was using default images when there were no featured images defined, and the default images were being dynamically added as background images. The div was set to a defined height, and the whole “responsive image” thing just wasn’t working the way it would with an actual image! After much trial and error, we finally decided that just setting a whole bunch of breakpoints for those images was probably the best way to go.

… Except I wasn’t happy with that. So I kept digging, and came across the article “Simple Responsive Images With CSS Background Images” by Stephen Thomas that helped me devise a much better solution!

The Solution

The short version is that we moved the background-image property to a span within the div, added a role of “img” and an Aria label to the containing div (for accessibility), and added the css to scale the images correctly. I won’t bore you with details here, but I definitely suggest reading the above article if you’re interested in learning more!

The Code

HTML

<a href=”<?php echo get_permalink(); ?>”>
<div class=”news-image” role=”img”>
<span id=”image-inner” style=”background-image: url(‘<?php echo $src[0]; ?>’);”></span>
</div>
</a>

CSS

.news-image {
display: inline-block;
width: 100%;
font-size: 0;
line-height: 0;
vertical-align: middle;
background-size: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-image: url(../../images/coa_xsmall.png);
background-color: #1E3B66;
}

.news-image #image-inner {
display: block;
height: 0;
padding-top: 58.3%;
background-size: cover;
}

Featured images show up where they’re supposed to and are beautifully responsive. On the posts without featured images, the default images shows up and scales beautifully as well! Everything’s the same ratio, and the client is thrilled. As a bonus, our stylesheet is a few lines shorter!

… Now, I haven’t tested this in IE8 yet, but considering that the current number of visitors using IE8 is about 0.4%, I think we’re probably safe not to worry about it. Heck, even 9 & 10 only amount to about 1.2% of visitors. Yay, Google Analytics, for saving my sanity!  LOL

And now, if you’ll excuse me, I have a code fix to push to stage. 🙂