Hi,

is there any way so I can make a responsive image style for background images?

Thanks.

Comments

Jaypan’s picture

You can set breakpoints and change the background image based on breakpoint.

.some_element {
  background-image: url(/path/to/mobile-image.jpg);
}

@media screen and (min-width: 768px) {
  .some_element {
    background-image: url(/path/to/tablet-image.jpg);
  }
}

@media screen and (min-width: 1024px) {
  .some_element {
    background-image: url(/path/to/desktop-image.jpg);
  }
}

If you want to use image styles, it becomes a little more tricky. You'll first need to upload your source images to the files directory. Then you will have to figure out what the URL should be using something like this for each image style. You will then use those URLs in your CSS:

$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl('public://my-image.png');

Note that you'll need to change 'thumbnail' to the machine name of the style you want to output. Also note that you can't use PHP in CSS files, so you're going to have to use this PHP code just to figure out what the URLs should be. This code likely will not become part of your final code.

sstavridis’s picture

Thanks! I'll try it!