Examples
HTML Responsive Image
Implementing Responsive Images
HTML responsive image uses <img> with srcset for device adaptability.
Understanding Responsive Images
Responsive images are crucial for delivering the best user experience across different devices. By using the <img> tag along with the srcset attribute, you can ensure that images are appropriately sized for the screen resolution and size of the device being used.
Basic Syntax of srcset
The srcset attribute allows you to define a list of image sources with descriptors that tell the browser when to use each image. Here's a basic example:
In this code, the browser will choose between medium.jpg and large.jpg based on the device's width. The descriptors 600w and 1200w indicate the width of the images in pixels.
Using sizes with srcset
The sizes attribute can be used alongside srcset to define the layout width of the image. This helps the browser make a more informed decision about which image to load. Consider the following example:
Here, the sizes attribute specifies that if the viewport is less than or equal to 600 pixels wide, the image should be rendered at 480 pixels wide. Otherwise, it should be 800 pixels wide. This allows for more efficient loading, especially on devices with varying screen sizes.
Art Direction with Picture Element
For more complex scenarios where you need to change the image depending on the device, such as different cropping or compositions, you can use the <picture> element. It provides more control over which image resource to apply:
In this example, the browser will use large.jpg if the viewport is at least 800 pixels wide, medium.jpg if it's at least 600 pixels, and small.jpg otherwise. This approach is beneficial for art direction, allowing you to serve different images based on screen size or other characteristics.
Best Practices for Responsive Images
- Optimize Images: Use image formats and compression levels that balance quality and file size.
- Test Across Devices: Ensure images look good on a range of devices and screen sizes.
- Use CDN: Consider using a Content Delivery Network to deliver images faster to users across the globe.
Examples
- Previous
- Semantic Layout
- Next
- Video Player