3

Is there any way to specify a fallback image for a background image using CSS?

Example

.container {
  background-image: url(pics/img.webp);
  background-image-fallback: url(pics/img.png);
}
AntoineB
  • 4,535
  • 5
  • 28
  • 61
  • 3
    Does this answer your question? [Fallback background-image if default doesn't exist](https://stackoverflow.com/questions/37588017/fallback-background-image-if-default-doesnt-exist) – Nijeesh Joshy Jan 23 '20 at 12:43
  • @NijeeshJoshy not really – Mo. Jun 14 '20 at 20:32
  • Simply stating your question is not a duplicate without explaining **why** it is not a duplicate will not succeed in getting your question reopened. – pppery Jun 15 '20 at 00:30

2 Answers2

2

You can use multiple images if the one doesn't exit, the second will be show.

.container {
      background-image: url(pics/img.webp), url(pics/img.png);
    }
Vikas Jadhav
  • 4,597
  • 2
  • 19
  • 37
  • 5
    technically speaking, this is not a fallback because the browser will try to load all the images – Temani Afif Jan 23 '20 at 15:06
  • 1
    Agree with you Temani afif – Vikas Jadhav Jan 23 '20 at 15:30
  • 2
    Yes, it will affect the page speed, as the browser tries to load both the images. The idea of specifying a fallback is to provide an alternative for an image if it could not be loaded, not load both. I am currently using this syntax but the Google PageSpeed test tool (Lighthouse) recommends providing a fallback what so ever. Should i look towards writing a different markup, or is there a way to specify the fallback while only using CSS? Thank you for your reply. – Karl Barnholdt Jan 24 '20 at 10:39
1

try like this.

.container {
  background: url((pics/img.webp) bottom center no-repeat,url((pics/img.webp) repeat;
}
Nethra
  • 579
  • 2
  • 8