Theming

Create a Responsive Image Style for Viewport-Sizing for Drupal 8, 9, 10, and 11

Last updated
Categories
Up-to-date with minor version
11.0.x

In this tutorial, we're going to add a responsive image style to an image field on the Article content type. This will add the srcset and sizes attributes to the output <img> element, providing media conditions, width descriptors, and a set of image sources for the browser to choose from, depending on the user device's viewport size.

This solution, especially when used in conjunction with CSS, will provide flexible, fluid, and faster-loading images for your site, and will work for probably 80% of use cases. It does not provide "art direction", that is, making cropping, aspect ratio, or orientation changes to an image. This solution also provides for different display-densities, like 1.5x and 2x image sources without the need for display-density descriptors.

Another benefit of this solution is that it uses the Responsive Image module's breakpoint configuration file, so there is no need for you to create a breakpoint file in your theme to implement this flavor of responsive image style.