- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using WebP Images with Fallback in CSS
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>
To set the images, the srcset attribute of the <source> element is used. The <source> tag allows a user to specify multiple media resources for elements, like <picture>, <video>, etc.
<source srcset="https://www.gstatic.com/webp/gallery/4.sm.webp" type="image/webp" /> <source srcset="https://www.gstatic.com/webp/gallery/4.sm.jpg" type="image/jpeg" /> <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg" />
Using the <source> tag, set alternative image files to allow the web browser to choose any one based on the web browser compatibility
The following examples illustrate this fallback.
Using the source element
To place the WebP images and an image with another format, we have used the <source> element on a web page −
<!DOCTYPE html> <html> <head> <style> * { margin: 2%; } </style> </head> <body> <picture> <source srcset="https://www.gstatic.com/webp/gallery/1.webp"> <img src="https://www.gstatic.com/webp/gallery/1.sm.jpg" /> </picture> </body> </html>
Using the source element multiple times
We have set multiple similar images with different extensions in the <source> in this example −
<!DOCTYPE html> <html> <head> <style> * { margin: 10px; } </style> </head> <body> <picture> <source srcset="https://www.gstatic.com/webp/gallery/4.sm.webp" type="image/webp" /> <source srcset="https://www.gstatic.com/webp/gallery/4.sm.jpg" type="image/jpeg" /> <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg" /> </picture> </body> </html>