How to make gallery images responsive?

In order for your images to be responsive they require CSS. The CSS will inform the image to stretch 100% of the available space and to automatically adjust the height.

img.responsive {
    width: 100%;
    height: auto;
}

Because you don’t want to apply this rule to all images, you’ll need to add a class on the target image which tells it to use these responsive rules.

<img class="responsive" src="https://wordpress.stackexchange.com/questions/214379/somepath/file.jpg" >

Add the CSS rule above to your style.css then add the class responsive to your image.

If you want test if this works first, open the text editor tab of the visual editor and find your image. Add the style attribute to the image or just add the relevant styles to the existing styles.

<img style="width:100%;height:auto;" src="https://wordpress.stackexchange.com/questions/214379/somepath/file.jpg" >

Because this is a manual process, the next question might be, ‘how do I automatically add a responsive class to an image inserted into the editor?”. In that case, you can make sure images added in the visual editor append the responsive class prior to being placed using the image_send_to_editor hook. You can place this in your functions.php or in a plugin but it really only matters in the admin section of your site.

add_filter('image_send_to_editor', 'wpse_20160112_filter_image_send_to_editor', 11, 8);

function wpse_20160112_filter_image_send_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt) {
    $responsive_content = str_replace('class="', 'class="responsive ', $html);

    return $responsive_content;
}

Galleries work off the same principal. You’ll need to establish the class rule ahead of time or add the styles directly to the output of the gallery images using the post_gallery and / or img_caption_shortcode hook.


Luckily for you, the solution is even easier. All you need is this CSS rule to make all your gallery images responsive.

.gallery .gallery-item img {
    width: 100%;
    height: auto;
}