With responsive image design, a web page can serve images in different formats or resolutions based on the screen resolution of the user's device. Images can display nicely on devices with various screen sizes and resolutions, and this can also help improve the web page's performance.
Let's explore how we can implement a webpage to serve images in different formats and sizes based on the screen resolution. Below is an example:
<picture> // load webp format in different sizes <source media="(min-width: 1025px)" srcset="image-full.webp" type="image/webp"> <source media="(max-width: 1024px)" srcset="image-1024.webp" type="image/webp"> <source media="(max-width: 768px)" srcset="image-768.webp" type="image/webp"> // if browser doesn't support webp // load jpg in different sizes <source media="(min-width: 1025px)" srcset="image-full.jpg" type="image/jpeg"> <source media="(max-width: 1024px)" srcset="image-1024.jpg" type="image/jpeg"> <source media="(max-width: 768px)" srcset="image-768.jpg" type="image/jpeg"> // fallback to standard img <img srcset="image-full.jpg 1024w, image-768.jpg 768w, image-500.jpg 500w" sizes="(max-width: 1024px) 1024px, (max-width: 768px) 768px, (max-width: 500px) 500px" src="image-full.jpg" alt="image description"> </picture>
The '<picture>' tag consists of a list of '<source>' tags. The first three are WebP images for different screen sizes. If the user's browser does not support the WebP format, it will try to load the next three '<source>' tags, which are in JPG format. Finally, there is an '<img>' tag as a fallback in case the browser does not support the '<source>' tag.
In the '<img>' tag, we also specify the 'srcset' and 'size' attributes to load different JPG images based on the screen size. The 'src' attribute is the final fallback option to load the image.
By using this approach, you can utilize different images with various formats and sizes for modern browsers to have better web page loading. It also ensures that older browsers are served with the standard '<img>' tag.