To implement responsive images with different sizes and resolutions, you can use the HTML <picture> element along with the <source> element. This allows you to specify multiple image sources based on various conditions, such as screen size and pixel density. Here's how you can achieve this:

  1. Prepare Your Images: Create different versions of your image in various sizes and resolutions. You'll need to have image files in different sizes and resolutions to serve to different devices and screen densities.

  2. HTML Markup: Use the <picture> element with multiple <source> elements and a <img> element as a fallback. Each <source> element should have the appropriate media query, srcset, and type attributes to define the image source based on conditions.

    Here's an example:

    html
    <picture> <!-- High resolution image for retina displays and high pixel density screens --> <source media="(min-width: 1200px)" srcset="path/to/image-lg.jpg 2x" type="image/jpeg" /> <!-- Medium resolution image for normal screens --> <source media="(min-width: 768px)" srcset="path/to/image-md.jpg 1x" type="image/jpeg" /> <!-- Small resolution image for small screens and low pixel density screens --> <source srcset="path/to/image-sm.jpg 0.5x" type="image/jpeg" /> <!-- Fallback image for browsers that do not support the picture element --> <img src="path/to/image-md.jpg" alt="Description of the image" /> </picture>

    In this example, we are providing three different image sources based on screen size and pixel density:

    • For screens with a minimum width of 1200 pixels (min-width: 1200px), we use a high-resolution image (2x) for retina displays.
    • For screens with a minimum width of 768 pixels (min-width: 768px), we use a medium-resolution image (1x).
    • For screens with smaller sizes or lower pixel density (default), we use a small-resolution image (0.5x).
  3. Responsive CSS: Use CSS to ensure that the images scale properly within their containers. You can set the image's max-width to 100% to make sure it doesn't exceed its container's width.

    css
    img { max-width: 100%; height: auto; }

With this setup, the browser will choose the appropriate image based on the screen size and pixel density of the user's device, ensuring the best possible display quality while optimizing loading times.

Have questions or queries?
Get in Touch