Responsive images / Fallback images

Hey all,

how would I approach the use of responsive images? Would the picture elements be used for that? And could someone explain to me how I would use that?

And how would I define fallback images? Not all browser or rather computer systems support webp, so a jpg or png fallback is still needed.

Any help much appreciated.

For a responsive image:

<picture>
<source srcset="main-w.jpg 1920w" media="(min-width: 768px)" />
<img class="img-fluid w-100" src="main-m.jpg" />
</picture>

This will load the main-w.jpg from source srcset on any device over 768px and the
main-m.jpg on devices under 768px.

the 1920w is the width of the main-w image.


For webp fallback:

<picture>
  <source srcset="main.webp" type="image/webp">
  <source srcset="main.jpg" type="image/jpeg"> 
  <img src="main.jpg" alt="Fall Back Image">
</picture>

You need to make sure you set the type to image/webp and image/jpeg


For background images, I use a custom build of modernizr, which you can get from here:
https://modernizr.com/download/?-webp-setclasses

once the link is open click on build and it will just give the webp function

you will know if it is working when in your browser console (inspect element) you first line of code will go from:

<html lang="de">

to this:

<html lang="de" class="webp webp-alpha webp-animation webp-lossless"> 

then I set my css up something like this:

#homePageHero {
 background: url("heroimage.jpg");
}

.webp #homePageHero {
 background: url("heroimage.webp"); 
}

2 Likes

Brilliant, thank you @richards . That’s a lot to take in, but I’ll have a play with that. So that should all be doable from within the picture element settings I take it?

Yes, the examples above are based on the <picture> element.

You can also use srcsets in an image, but I always find the picture element easier to code (just my personal preference)

That would look something like:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w">

There are some good articles on css-tricks:


You also might find this handy, it will resize your images and generate the html to add to your site.

1 Like

@fynn another thing that I should mention, if you are not using the BSS server, have a look in your server settings to see if they offer web optimisation, this might give you the option for converting jpgs to webp automatically, I just used it to optimise a wordpress site with 9000+ posts, all the jpgs are now webp if the browser supports them, if not it loads the original jpg.

1 Like