How can I set image sizes and still have responsive images using the srcset attribute?

The srcset attribute is constructed from images that are the same aspect ratio. Create a few of those and you’ll be ok.

add_image_size( 'compare-offer-box', 400, 300, true);
add_image_size( 'compare-offer-box-2', 800, 600, true);
add_image_size( 'compare-offer-box-3', 1200, 900, true);

for example. The fourth, boolean, argument tells WP to crop to the exact proportions.

To resize without cropping, use:

add_image_size( 'compare-offer-box', 400, 9999, false);
add_image_size( 'compare-offer-box-2', 800, 9999, false);
add_image_size( 'compare-offer-box-3', 1200, 9999, false);

This assumes you want a particular width image and then whatever height the proportions require. You’ll see some code around the web that uses values of 0 or null for the non-constrained dimension, but comments in the WP source code warn that this can have “unpredictable results.”

If you’d rather scale proportionately while constraining the height then just use a huge value for the width:

add_image_size( 'compare-offer-box', 9999, 400, false);
add_image_size( 'compare-offer-box-2', 9999, 800, false);
add_image_size( 'compare-offer-box-3', 9999, 1200, false);

If you want to maintain proportions but scale the image to fit within a certain space, say 400px by 400px, you can specify both maximum width and height but with cropping set to false:

add_image_size( 'compare-offer-box', 400, 400, false);

Note that if you are constraining by height then you may want to adjust the sizes attribute too, as that defaults to the width of the viewport with a maximum value of the specified image size’s width.

Don’t forget that you’ll then need to regenerate image sizes for your existing images. There are plugins that do this well: Search for Regenerate Thumbnails in the plugin repository.

Leave a Comment