We have a need to use the Responsive Image module. The key is that we want to be able to use the image (field_image) field with Responsive Image styles as a background and put the node's title on top of them.

How can we achieve this?

We have tried the following but this only fetches the original photo in a twig template. In other words, when i use Chrome Dev tools to see if it fetched the other images as part of the Responsive Image style settings, it does not fetch them.

<div class="wrapper">
    <div class="wrapper__image" style="background-image: url('{{file_url(content.field_image.0['#item'].entity.uri.value)}}>
    <div class="wrapper__content"> {# title goes here #} </div>

Sample image: Image with text on top

Currently we are using the out of the box Responsive Image twig template

{% if output_image_tag %}
  {{ img_element }}
{% else %}
    {% if sources %}
      Internet Explorer 9 doesn't recognise source elements that are wrapped in
      picture tags. See http://scottjehl.github.io/picturefill/#ie9
      <!--[if IE 9]><video style="display: none;"><![endif]-->
      {% for source_attributes in sources %}
        <source{{ source_attributes }}/>
      {% endfor %}
      <!--[if IE 9]></video><![endif]-->
    {% endif %}
    {# The controlling image, with the fallback image in srcset. #}
    {{ img_element }}
{% endif %}
  • I had to do the same thing and I just used a position: absolute image & title. I don't believe the picture element of the srcset is supported in CSS or anything of the like. – Chris Happy Feb 8 '18 at 18:44
  • I am just curious as I have not used the Responsive Image module... But I do know that you need to use a twig filter to call an image style in a twig template like that, e.g. file_url(content.field_image.0['#item'].entity.uri.value) | image_style('responsive_style'). Installing the module "Twig Tweak" makes this filter available. I wonder if Drupal would replace the image as long as that filter was applied?? – Prestosaurus Feb 13 '18 at 17:07

What you're trying isn't going to work on a background image. You'd need to do this yourself with javascript. How i've done it previously is added data attributes to the div for each breakpoint e.g.

<div data-mobile-image="mobilestylename/aaa.jpg" data-desktop-image="desktopstylename/aaa.jpg">

Then in javscript use matchmedia or a body class if its already being added by your theme to know which breakpoint you are in and then do

var mobile_image = $('.mydiv').data('mobile-image');

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.