How to Fix Blurry Images in WordPress 4.4 from srcset and sizes


In WordPress 4.4 they added a big feature: responsive images using srcset and sizes for all content images.

This is amazing. Since WordPress is a hugely popular framework, the amount of bandwidth saved is astronomical. I’m really proud of the WordPress team for implementing this.

But… there are some blurry images. It’s not a perfect one-size fits all solution for every site.

If your images are full screen width, you’ll get a blurry image on wide screens because WordPress is telling your browser to use an image smaller than your browser width. It’s a simple fix, and if you don’t want to read my mini-rant, you can skip to the fix.

The Backwards Way To Fix It

When I was googling to see what others have done to fix this, the only answer I was coming across was to entirely remove the srcset responsive image approach. Go back to a plain ol’ img tag, thank you very much.

I get it. Images are much easier that way. But I don’t think the importance of what srcset accomplishes was understood.

When you use srcset with your image, you provide your browser with a bunch of different versions of your image from small ones to giganto ones. When you go to your site, your browser quickly scans the list of images and picks out the one it needs. That way you don’t download a 2000px wide desktop image onto your phone. You download the 400px one. When you’re paying for your data usage, that’s a big deal.

So, if you’re getting blurry images in WordPress, don’t throw the baby out with the bath water.

The Fix

Here’s a snippet to drop into your functions.php file that will keep the benefits of srcset responsive images and never give you a blurry image. It won’t be a fine-tuned, Italian leather, srcset machine, but it’s far better than axing it entirely.

function osteo_img_sizes($sizes) {
	return '100vw';
}
add_filter( 'wp_calculate_image_sizes', 'osteo_img_sizes');

This filter overrides WordPress’s default sizes attribute to tell your browser, “Don’t serve images larger than the screen width.” VW here stands for viewport width (your browser width).

That’s it. It’s not perfect, but it serves the people that need it most: people on mobile devices with a slow and/or costly connection.


One response to “How to Fix Blurry Images in WordPress 4.4 from srcset and sizes”

  1. Your articles explain technical concepts in a way that makes sense to noobs such as myself. I think many people quit early when it comes to web development because they get overwhelmed (and then feel dumb), and you’re helping to stem the tide. Keep it up!

    Like

Leave a comment