Responsive Images - Background Image

My theme uses background images for all the post featured images. The problem with this is I can’t manage to get Responsive images working.

I just don’t understand how to translate the code to work with background url, rather than simple <img>.

cheers
Andrew

Hey, have you got some sample code of the config and the template code you’re using?

{{#if feature_image}}
	<div class="item-image" style="background-image: url({{feature_image}})"></div>
{{/if}}

Using config example in tutorial, and Casper theme. It works if I do standard example with <img> tag.

Try wrapping the value in single quotes:

{{#if feature_image}}
	<div class="item-image" style="background-image: url('{{feature_image}}')"></div>
{{/if}}

The quotes are not the issue. I can get featured images to work, but my understanding is the img code for responsive images is quite complex. I don’t know how this example code can be converted to work as a background-image as it doesn’t use an img tag, it uses a URL. I’ve tried a few options but nothing works.

<img class=“post-image”
srcset="{{img_url feature_image size=“s”}} 300w,
{{img_url feature_image size=“m”}} 600w,
{{img_url feature_image size=“l”}} 1000w,
{{img_url feature_image size=“xl”}} 2000w"
sizes="(max-width: 1000px) 400px, 700px"
src="{{img_url feature_image size=“m”}}"
alt="{{title}}"
/>

@andrewmc the closest you can get with CSS is the image-set() function but that is only for resolution (DPI), not responsive images as per HTML’s srcset attribute. It also has poor browser support.

If you need responsive images then you’d need to change your design to not use background images.

1 Like