How to Set Responsive Images in Drupal 9
Optimal user experience is an essential aspect of web development, and key to that is the assurance of correctly sized images. If some of your visitors are using a mobile device, the use of very large images that are suitable instead for desktop is not optimal.
Ensuring the right-sized image for the right device is what's referred to as "responsive images."
Responsive images help with faster loading speeds, save bandwidth, and give visitors a better experience overall.
This post will focus on setting responsive images in Drupal 9. How-tos for previous versions of Drupal can be found here:
- Picture Module: Building Responsive Images in Drupal 7, and
- How to Set Up Responsive Images in Drupal 8.
For Drupal 9, the key steps that need to be executed are as follows:
- Install the Responsive Image module (using Composer or Drupal UI).
- Setup the breakpoints.
- Create image styles.
- Set up the responsive image.
- Assign the responsive image style to the image field.
- Export configurations to code.
Step 1: Install the Responsive Image Module.
As was also the case with Drupal 8, the Responsive Image Module is part of Drupal core. For this reason, additional modules do not need to be added in Drupal 9.
The responsive image module provides an image formatter and breakpoint mappings to output responsive images using the HTML5 picture tag. This allows devices to display larger or smaller images based on the screen size.
Steps Via Composer
- Open up your command line tool. (We like to use iTerm with oh-my-ZSH).
- Travel to your site directory using “cd.”
- Run the command: “drush en responsive image.”
Steps Via Drupal UI
- Once logged in as admin, go to “Extend” in the Drupal admin menu, or visit the URL path: /admin/modules
- Then, in the list of modules, scroll down until you find “Responsive Image” and click the checkbox next to it. Helpful tip: you can also search for the module name in the search box at the top.
- Click on “Install” at the very bottom of the list.
Step 2: Set Up the Breakpoints.
Now is when we need to decide, and create a few breakpoints for our image styles. This is where we decide how many, and at which screen size, we want to show a different sized image. Some default themes already have the “.breakpoints.yml” file, so it might be worth checking for that in your theme first.
If you have a custom theme, go to your editor of choice. We like to use Sublime Text, Atom, or Visual studio code.
In Drupal 9, the root of your theme directory will be located at “/themes/my_theme_name” or “/themes/custom/my_theme_name”, depending on your setup. In the root of your theme directory, create a file called "my_theme_name.breakpoints.yml", and replace "my_theme_name" with the real name of your theme.
For this tutorial, I will call my theme "myd9demo".
Below you will find an example of a breakpoint setup for this theme. We’re setting up three breakpoints. One we would use for mobile phones, one for tablets, and one for Desktop. But this is just an example, please choose a breakpoint that works best for your website, and your theme, as you may already have a grid system with breakpoints configured in your CSS.
mediaQuery: 'all and (min-width: 768px)'
mediaQuery: 'all and (min-width: 1200px)'
Each breakpoint will tell Drupal what image size to load for each assigned mediaQuery. For example, we can load an image for mobile devices using a smaller image style for the breakpoint at min-width: 0px. When the browser is at min-width: 768px we can load our “tablet” image style, and at min-width: 1200px, we can load our desktop or full size images.
It is important to note that the breakpoints weight should be listed from smallest mediaQuery to largest mediaQuery. This allows you to follow a mobile-first approach, as your Grid system (if you have one) is likely following a mobile-first approach as well.
The multipliers attribute allows us to display a crisper image for HD and retina display. A great example of that would be to have an image style of 1000 X 1000 for a normal screen, but on a retina ready screen, you might load an image at 2000 X 2000.
Step 3: Create Your Image Styles.
Now we need to create the image sizes for the different breakpoints and different resolution sizes. To do that, in the header, go to configuration > Media > Image styles. Or go to: /admin/config/media/image-styles.
Next you'll need to create an image style for the breakpoint and resolution sizes you set up in your my_theme_name.breakpoints.yml. Since we created three breakpoints in our breakpoint.yml file, and we are setting up two resolution sizes for retina ready, and non retina ready screens, we will have a total of six image styles. You could label them as follows:
- Mobile 1X
- Mobile 2X
- Tablet 1X
- Tablet 2X
- Desktop 1X
- Desktop 2X
To start creating your image styles, follow these steps.
- Click the "Add image style" button in the top left corner.
- Type in the name of your image style. It’s better if your image style name is descriptive. As you will likely be setting up several image styles throughout your project.
- Click “Create new style”.
- When you’re redirected to your new image style, using the dropdown under “Effect”, choose scale and crop. *Pro-tip:* for even better transparency and cropping capabilities, try adding the “Focal Point” Module. It will allow you to select in which area/direction your image would scale and crop.
Click the “add” button.
- Enter the size of your image style. As an example, our mobile image might be 400x200, and our retina ready mobile image would be 800x400.
- Click "Save".
- Repeat steps 1-7 until you’ve created all six images styles.
For each image style we have used the scale and crop effect to resize and crop the images uploaded automatically.
Below are a few examples of what this might look like:
Step 4: Set Up the Responsive Image Styles.
Now we will assign the image styles to the breakpoints. Go to: Administration > Configuration > Media, or go to “/admin/config/media/responsive-image-style” and click on "Add responsive image style".
For this tutorial, I will call it "Article Image" since this will be used for the main image in our article content type. We will select our theme (in this example it's "My D9 demo").
Then select the correct image styles for each breakpoint. In the Drupal UI, it will display the breakpoints from largest to the smallest. For our retina ready Desktop image, open up the dropdown called “Large 2X and select the image style “Desktop 2X”. For our non-retina Desktop, select “Desktop 1X”. So on and so forth until you’ve selected the correct image style, for each breakpoint and screen resolution.
At the end of the form, you will find the Fallback option. This will be used in case the responsive images are not available. You should select the smallest image style you created here, the same as for mobile. Select the smallest responsive image style effect you created in the Fallback option.
Step 5: Assign the Responsive Image Style to the Image Field.
Let's recap. So far we’ve set breakpoints and resolution sizes in our theme, to be used for our images. We then created six image styles, one for each screen size and resolution. Then we connected the created image styles to our created breakpoints.
Now it's time to attach the responsive image style to one of our image fields. This way, when an image that is printed using the "display" of a content type, it will be printed using this Responsive Image style.
Go to Administration > Structure, or go to “/admin/structure/type” in your address bar. On the content type you want to change ( in this example, it is an article ), click on the arrow next to "Manage fields" and select "Manage Display".
On the Manage Display form, on your image field, click on the dropdown under the "Format" for your image and select the "Responsive image" option.
After that, click the gear icon located on the far right hand side, and select your Responsive image style ("Article image" in our example).
Click save and we are done! Well almost :)
To check, add a new content piece and add an image to the image field (make sure you are in the right content type). Resize your browser to view the page like a tablet or a mobile device.
Right click on the image and click "inspect", you should see an HTML5 <picture> attribute with many different image styles within breakpoints.
Step 6: Export Your Configurations to Code.
The very last step is to export all of these Drupal configurations into code. We do this for several reasons, two of which are:
- To ensure our settings are saved, and can be imported to your sites in the future, while allowing you to overwrite configuration if they are modified in the future.
- To allow us to commit something to git, leaving us a nice trail/breadcrumb of our work.
There are two ways of doing this. Either through the UI and exporting all configs, or through your command line using Drush (this is the recommended way if you have a server running Drush).
Below are the steps for both.
Via Command Line with Drush
- Use your command line tool, “cd” into your website's root directory.
- Then run the following command: “drush cex.” If you’re running your site locally, you might be using something like Docker and docksal, in this case, you would run “fin drush cex”
- Once this is run, you will get a list of modified configurations and files that will be overwritten in your /config/default directory.
- Press the enter key to accept.
- Go to the “Configuration > Development > Configuration Synchronization” > Export or go to the path: “admin/config/development/configuration/full/export”
- Click the export button.
- This will export the entire configuration folder into a zip.
After this, the only thing left to do is push your code up to whatever git repository you use, and celebrate your achievement.
Our team here at Promet Source is devoted to channeling our collective brainpower toward helping the Drupal community to migrate to Drupal 9 ASAP and optimize all that Drupal 9 has to offer. We hope that you found this tutorial helpful. Any other questions? Let us know what we can do for you.
*Special thanks to Mary Chris Casis and Luc Bézier for their expertise and significant contributions to this prior to publication.