Divi WordPress Theme
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

WordPress fix making the gallery shortcode responsive

Discussion in 'Misc WordPress Requests' started by fcwhitford, Apr 3, 2018.

  1. fcwhitford

    Guest

    making the gallery shortcode responsive, by fcwhitford

    The gallery shortcode is cheap and cheerful but useful for adding a collection of images to a post without the complication of a plugin like NextGen Gallery, but it is not responsive – the number of columns have to be specified. To make this adapt to the browser width I’ve added the following to the theme:

    1) in functions.php, disable the inline CSS which is normally generated and force the number of columns to 0 to prevent breaks being inserted:

    add_filter('use_default_gallery_style', function ($html5) {
    return false; // suppress default inline styles
    });
    add_filter('shortcode_atts_gallery', function ($atts) {
    $atts['columns'] = 0; // allow lines to wrap as required
    return $atts;
    });

    2) add new CSS rules in style.css:

    div.gallery {
    clear: both;
    }
    .gallery-item {
    display: inline-block;
    text-align: center;
    vertical-align: middle;
    }
    .gallery-size-thumbnail .gallery-item {
    width: 120px;
    }
    .gallery-size-medium .gallery-item {
    width: 205px;
    }
    .gallery-size-large .gallery-item {
    width: 730px;
    }

    The widths given match the image sizes set in the dashboard media settings with a bit added to space the thumbnails. (The last rule is probably superfluous.) No styling is added for the images because these use the same style rules as other images in posts.
    The key here is using display:inline-block which causes the images to be added along a line, like characters in text, and wrap on to a new line when necessary. The fixed width is not essential but looks better as the images form a regular grid. If all the images were the same width it wouldn’t be necessary to specify a width.

    making the gallery shortcode responsive
     
    #1

Share This Page

Monarch Social Sharing Plugin