Responsive Images in Drupal 8

The days of fixed-width websites are long behind us, and with fluid widths came fluid images. In many cases, we don’t want to display the same image size on a mobile and on a desktop, because we truly don't need a 2000px wide image on a 480px device. Or we want to display a completely different image at some breakpoint.

For this we have a HTML5 <picture> element which can contain a multiple <source> elements with srcset and media attributes. The browsers choose the right source based on a media query.

In my case, I had to show completely different image sizes on mobile vs. desktop.

Responsive image 1

 

There are two core modules in Drupal 8 that allow you to do exactly that.

The first one is Breakpoint. It manages breakpoints and breakpoint groups for responsive design and because it doesn't have a user interface you have to define these breakpoints in your theme.breakpoints.yml file (For more information about the Breakpoint module see the online documentation).

 

theme.mobile:
  label: mobile
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
theme.desktop:
  label: desktop
  mediaQuery: 'all and (min-width: 1024px)'
  weight: 2
  multipliers:
    - 1x

The second module is Responsive Image. Make sure you enable it before you start as it's not enabled by default. This module provides an image formatter and breakpoint mappings to output responsive images using the HTML5 picture tag.

After you define the "normal" image styles for different breakpoints you can create a new Responsive image style and set the appropriate image styles for each breakpoint.

Responsive image 2

 

It's time for the last step. Select the Responsive image formatter for your field in "Manage Display" section of your content type and choose the newly created responsive image style.

 

Responsive image 3

 

There you have it. An image that has been specifically sized for the screen has been successfully loaded.