Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Optimizing Your Themes for Responsive Images in WordPress

Optimizing Your Themes for Responsive Images in WordPress

This presentation on making use of the responsive images functionality in WordPress was given at the 2016 WordCamp St. Louis at Washington University on May 14, 2016.


Joe McGill

May 14, 2016


  1. Optimizing Your Themes For Responsive Images In WordPress Joe McGill

  2. An overview of responsive 
 image use cases • Display

    size (resolution/viewport) • Device density (retina devices) • Art direction More at: usecases.responsiveimages.org
  3. Display Size resolution differences viewport layout changes

  4. 2x 1x Display Density

  5. Art Direction

  6. the image element <img src="file.jpg" alt="…">

  7. Responsive Image HTML • srcset (x descriptors) • srcset (w

    descriptors) + sizes • The <picture> element
  8. srcset + x descriptors <img src="file.jpg" alt="…" srcset="file.jpg, file-2x.jpg 2x">

  9. srcset + w descriptors <img src="file.jpg" alt="…" srcset="file.jpg 300w, file-2x.jpg

    600w, file-4x.jpg 1200w"> NOTE: The browser doesn’t know the display size of the 
 image, so it assumes 100% of the viewport width.
  10. srcset + sizes <img src="file.jpg" alt="…" srcset="file.jpg 400w, file-2x.jpg 800w,

    file-3x.jpg 1200w" sizes="(max-width: 400px) 100vw, (max-width: 980px) 50vw, 400px" >
  11. <picture> <picture> <source srcset="large.jpg" media="(min-width: 800px)"> <img src="small.jpg" alt="…"> <picture>

  12. WordPress ❤ ’s srcset + sizes • WordPress automatically creates

    extra sizes when you upload an image (e.g., thumbnail, medium, large, etc.) • Add your own custom sizes with add_image_size() • WP includes same ratio image sizes in srcset
  13. add_image_size() // Soft resize add_image_size( 'custom-size', 220, 180 ); //

    Hard crop add_image_size( 'custom-size', 220, 180, true );
  14. The Sizes Dilemma • The sizes attribute tells the browser

    about the layout of the image. • The image layout is dependent on your theme’s CSS rules.
  15. A smart default <img src="…" width="600" height="400" alt="…" > sizes="(max-width:

    600px) 100vw, 600px"
  16. Customizing the sizes attribute add_filter( 'wp_calculate_image_sizes', 'my_sizes_filter' ); function my_sizes_filter()

    { return '(max-width: 37em) 85vw, (max-width: 45em) 67vw, 840px'; } WP.org code reference
  17. Customizing the sizes attribute add_filter( 'wp_calculate_image_sizes', 'my_sizes_filter', 10, 2 );

    function my_sizes_filter( $sizes, $size ) { if ( 'medium' === $size ) { $sizes = '(max-width: 37em) 85vw, (max-width: 45em) 67vw, 840px'; } return $sizes; }
  18. Calculating the sizes attribute • Start your browser at a

    small width and write down image widths at each breakpoint. • Tip: use calc() to combine relative and fixed size calculations.
  19. THANK YOU Joe McGill @joemcgill • joemcgill.net