With more and more users using their phones to search the web, the demand to create faster loading web pages is ever increasing. A common issue that developers face when looking to reduce page load time is image optimization. Beyond image compression, however, there is not much more you can do to image without sacrificing the quality of the image - until now. Thanks to a recent update to Drupal 8, the Responsive Image Module allows for the cropping or scaling of images at any desired breakpoint. This means you no longer have to load a 1900px+ size image on mobile devices, greatly reducing download time.
Additionally, from a front-end perspective, you are no longer constrained to one image style across all breakpoints. You can switch up the crops and scale sizes from one breakpoint to another, giving you more design freedom when using image styles.
To use this powerful module, there are just a few simple steps to get you on your way.
The yourtheme.breakpoint.yml file allows you to define all the breakpoints used in your site.
This file is placed within the root of your project, where your
.info files live. The essential aspects of this file are:
Below is an example of a basic
yourtheme.breakpoint.yml file to get started:
mediaQuery: 'all and (min-width: 640px) and (max-width: 991px)'
mediaQuery: 'all and (min-width: 992px) and (max-width: 1199px)'
label: extra large
mediaQuery: 'all and (min-width: 1200px)'
Once the .breakpoint.yml file has been create, install the Responsive Image module within the Extend section.
Next, you will need to create an image style for each breakpoint. I typically make sure I do two things when creating these image styles:
Now that the module is installed and your image styles are created, you are ready to create your first Responsive Image Style.
Label your responsive image style, and select a breakpoint group. It is important to select the breakpoint group you created in the previous step (typically called your theme name), as this will allow you to add an image style for each breakpoint group.
The next page you will see is where you can set the image styles for all your breakpoints you defined in your
mytheme.breakpoints.yml file. There are a few ways to define your image styles for each breakpoint here, but we will just go over one simple one for now:
And that's it! Repeat the steps above for each breakpoint, and you will have successfully created a responsive image style. Now it is time to use that style on a field.
Using a responsive image style is very similar to using a basic image style.
Navigate to the display mode that contains your image field, and edit that image by clicking the gear on the right
From there, choose the image style name you created in the beginning of step four, update, and finally, save your field.