Using WebP Images with Fallback in CSS

CSSWeb DevelopmentFront End Technology

To render a huge number of images in a website, it is advisable to use webp format as it provides better compression.

We use the <picture> element to provide a fallback for unsupported browsers −

<picture>
   <source srcset="filename.webp" type="image/webp">
   <source srcset=" filename.jpg" type="image/jpeg">
   <img src=" filename.jpg">
</picture>

The following examples illustrate this fallback.

Example

<!DOCTYPE html>
<html>
<head>
<style>
* {
   margin: 2%;
}
</style>
</head>
<body>
<picture>
   <source srcset="sky.webp">
   <img src="sky.jpg" />
</picture>
</body>
</html>

Output

This will produce the following result −

Example

<!DOCTYPE html>
<html>
<head>
<style>
* {
   margin: 10px;
}
</style>
</head>
<body>
<picture>
   <source srcset="tree.webp" type="image/webp" />
   <source srcset="tree.jpg" type="image/jpeg" />
   <img src="tree.jpg" />
</picture>
</body>
</html>

Output

This will produce the following result −

raja
Published on 13-Mar-2021 12:04:05
Advertisements