Academy / Advanced Level: HTML and CSS
Advanced Responsive Web Design Techniques
Responsive Images with srcset and sizes
Responsive images are crucial for ensuring that images load quickly and look great on all devices. By using the srcset and sizes attributes, you can provide different image sizes for various screen resolutions and devices, ensuring the best quality with minimal loading time.
Example: Using srcset and sizes
<img
src="image-small.jpg"
srcset="image-small.jpg 600w, image-medium.jpg 1200w, image-large.jpg 1800w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw"
alt="Responsive image example">
srcset: Defines the image files to use for different screen widths (600w, 1200w, 1800w represent the image widths in pixels).sizes: Defines the size of the image relative to the viewport width. This ensures the browser picks the correct image for the device.
In this example:
- On screens 600px or smaller, the image takes up 100% of the viewport width.
- On screens between 601px and 1200px, the image takes up 50% of the viewport width.
- On larger screens, it takes up 33% of the viewport width.