Fallback background-image if default doesn't exist

后端 未结 5 718
忘掉有多难
忘掉有多难 2020-11-29 09:43

I want to set an image as a background, however the image name might be either bg.png or bg.jpg.

Is there any non-javascript way to create

5条回答
  •  抹茶落季
    2020-11-29 10:42

    To specify multiple possible backgrounds, you could do:

      background-color: green;
      background-image: url('bg.png'), url('bg.jpg');
    

    This will set the background to bg.png if it exists. If it doesn't exist, it will be set to bg.jpg. If none of those images exist, the background will be set to the static green color.

    Note that it will prioritize whatever image is specified first. So if both images exist, it will choose the bg.png over the bg.jpg.

    Check out the demo here. Test it by breaking any of the image urls'.

提交回复
热议问题