0

When using the core Image module, the height and width of images are automatically set. But when I use the Responsive Images module and a Responsive Image style, then no height or width is set.

Users don't like this because it makes the website look janky because images can pop into place and change the layout suddenly. Google doesn't like this because it slows down the page. When testing with Lighthouse, it gives the following recommendation:

Set an explicit width and height on image elements to reduce layout shifts and improve CLS. Learn more

There was also an article in Smashing Magazine this year about setting height and width.

How can I do this in the Responsive Image module?

1

The code for this is actually pretty simple.

There are a few important points.

  1. For this to work, all of the responsive images in a single responsive image style must have the same aspect ratio. They can have different heights and widths, but the aspect ratio must be the same.
  2. You have to set the height and width to be the maximum possible (the height and width of the largest image in the responsive image style).

Assuming your responsive image style has a machine name of hero, here's some example code:

/**
 * Implements hook_preprocess_responsive_image() for MYMODULE.
 *
 * {@inheritDoc}
 */
function MYMODULE_preprocess_responsive_image(&$variables) {
  $style_id = $variables['responsive_image_style_id'];
  if ($style_id === 'hero') {
    // Set the height + width to the aspect ratio for all images.
    // Use the largest possible height + width that may be displayed.
    $variables['img_element']['#attributes']['height'] = 450;
    $variables['img_element']['#attributes']['width'] = 800;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.