DEV Community

Filimonov
Filimonov

Posted on

 

Configuring Adaptive Image Styles in Drupal 8

In my previous article I already wrote that all pictures should have an image style, but sometimes that might not be enough.

Let's say there is a banner that takes up the entire width of the screen. I set an image style where the picture will be scaled to a width of 1920 pixels. And if for computers and laptops this is the right size, for mobile devices it is too much.

In HTML there is a picture tag that substitutes the desired image depending on the screen width.
In Drupal it is implemented through a kernel module - responsive image.

Enable module Responsive image:

drush en responsive_image -y
Enter fullscreen mode Exit fullscreen mode

In the folder with your theme should be a file with breakpoints.

/themes/custom/themename/themename.breakpoints.yml
Enter fullscreen mode Exit fullscreen mode

I use widths: 480, 768, 980, 1180.
Consequently, the contents of the file look like this:

themename.sp:
  label: smalltouch portrait
  mediaQuery: 'all and (min-width: 1px) and (max-width: 479px)'
  weight: 4
  multipliers:
    - 1x
themename.sl:
  label: smalltouch landscape
  mediaQuery: 'all and (min-width: 480px) and (max-width: 767px)'
  weight: 3
  multipliers:
    - 1x
themename.tp:
  label: tablet portrait
  mediaQuery: 'all and (min-width: 768px) and (max-width: 979px)'
  weight: 2
  multipliers:
    - 1x
themename.tl:
  label: tablet landscape
  mediaQuery: 'all and (min-width: 980px) and (max-width: 1179px)'
  weight: 1
  multipliers:
    - 1x
themename.desktop:
  label: desktop
  mediaQuery: 'all and (min-width: 1180px)'
  weight: 0
  multipliers:
    - 2x
Enter fullscreen mode Exit fullscreen mode

Now for each breakpoint you have to create an image style whose width should be equal to the maximum width of the breakpoint.

For example: For tablet portrait, the width in the image style should be 979px, since max-width for tablet portrait = 979px.

I mark with a W that the image style is scaled by width only / Width

Go to the "Adaptive Image Styles" page and add a new one:

/admin/config/media/responsive-image-style
Enter fullscreen mode Exit fullscreen mode

In "Breakpoint Group" - choose your topic.<br>

For each breakpoint we set a predefined image style.

Image description

And in the "Backup Image Style" we set the desktop style. That is why, for the breakpoint desktop image style can not be set.

Desktop Retina is an image style for dual pixel monitors, which is often found on Apple computers.

Once everything is set for each width - click save and the adaptive image style will be created.

Go to control the display of the entity that displays the image:

To make this setting appear - click on the gear icon

In the settings, select the adaptive image style that we created → Save.

If the images are not updated - use the command:

drush image-flush --all ; drush cr
Enter fullscreen mode Exit fullscreen mode

Top comments (0)