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
Tweet

More Decks by Joe McGill

Other Decks in Technology

Transcript

  1. An overview of responsive 
 image use cases • Display

    size (resolution/viewport) • Device density (retina devices) • Art direction More at: usecases.responsiveimages.org
  2. Responsive Image HTML • srcset (x descriptors) • srcset (w

    descriptors) + sizes • The <picture> element
  3. 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.
  4. 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" >
  5. 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
  6. add_image_size() // Soft resize add_image_size( 'custom-size', 220, 180 ); //

    Hard crop add_image_size( 'custom-size', 220, 180, true );
  7. 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.
  8. 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
  9. 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; }
  10. 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.