0

I would like to render an image as background image in my Twig template. To optimize my resources I'd like to use a responsive image but I cannot find a way to use it for background images.

For a standard image I would use something like

img src="{{ file_url(node.field_with_image.entity.uri.value) }}" alt="my_alt" class="my_class">

How can I achieve that with a background image?

0

You should definitely have a look at Background Images Formatter.

It contains a submodule to handle responsive images as well.

Either use that or check how they are doing it.

  • Is there any way to access the image within the twig with something like {{ content.my_field }} ? – Tibo May 30 '18 at 14:11
  • Something like {{ node.my_field.entity.uri.value | image_style('thumbnail') }} but for responsive images ? – Tibo May 30 '18 at 14:19
0

Responsive images in Drupal 8 rely on HTML picture element and srcset attribute. That's not something that can be applied to background. Instead you need to user media queries in your CSS to specify different background images for different screen sizes.

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.