Responsive Images in HTML: A Practical Guide

html responsive images

Before diving into the specifics of responsive images, it’s important to understand the basics of adding and manipulating images in HTML. To insert an image, the <img> tag is used, which is an “empty element” and does not require a closing tag. Key attributes of this tag include:

  • src: Specifies the image’s relative or absolute file location.
  • alt: Adds alternate text for the image, which is crucial for accessibility and SEO.
  • width: Sets the width of the image.
  • height: Sets the height of the image.

To add an image, follow these steps:

  1. Upload the image file to your server or hosting.
  2. Access the theme or HTML folder where your web page is located.
  3. Add the <img> tag to your HTML and set the src attribute to point to the image location.
  4. Optionally, set the width and height attributes to define the image size.
  5. Always add an alt attribute to describe the image.
  6. Save the changes to your HTML file.

In addition to these basics, images in HTML can be used in various interactive ways, such as creating an image button by placing the <img> tag inside a <button> tag, creating a clickable image link with <img> and <a> tags together, or overlaying text on an image by using a div with a class named “image-container” and adding an image within it.

What Are Responsive Images?

By dynamically adapting to changes in screen resolution, screen size, or other differences among client devices, responsive images are part of a RWD [responsive web design] process that ensures that a site can accommodate environmental constraints: display dimensions and quality, connectivity and network conditions, available input types. You can place responsive images in various locations, including website content, headers, and backgrounds.

Responsive images must render at different pixel ratios on different devices to reflect the pixel depth of the viewing device. In addition, a responsive or fluid layout must be able to squeeze or stretch to cater to changes in screen size. All that requires multiple images being available in several resolutions to appropriately scale the screen across various sizes.

This article answers these questions:

Why Should You Create Responsive Images in HTML?

According to Statista, more than 90% of internet users worldwide access the web on mobile devices. Since most webpages contain images, let alone that search engines measure web performance through image metrics, responsive images help achieve optimal performance and deliver a positive user experience.

Generally, browsers preload images before parsing CSS, i.e., before the site’s JavaScript detects the viewport width based on which to modify images. That’s why HTML is a more ideal choice than CSS for coding responsive images.

For more details, see responsive image CSS.

How Do You Create Responsive Images in HTML?

You can create responsive images in HTML in the three ways below.

Art Direction

As an alternative to the srcset and sizes attributes, HTML’s <picture> element enables you to define breakpoints, which are critical points at which a page’s design changes for an enhanced user experience. You can display a different image at each breakpoint, a technique known as art-directing images.

The sample code below provides three options for displaying the image of a house:

  • A zoomed-out image that shows the house and its surroundings
  • A regular image that shows only the house
  • A zoomed-in image that shows the important elements of the house
<picture>
  <source
    srcset="house-zoomed-out.jpg"
    media="(min-width: 1200px)"
  />
  <source
    srcset="house-normal.jpg"
    media="(min-width: 800px)"
  />
  <img
    src="house-zoomed-in.jpg"
    alt="Baby Sleeping"
  />
</picture>

This code creates two breakpoints:

  • If the screen size is less than 1,200 px., which is too small to show the entire image, switch the image to house-normal.jpg.
  • If the screen size is less than 800 px., show the zoomed-in version so that viewers can still see the important elements of the house even on small screens.

To learn how to automate tasks related to responsive images, see the documentation on combining responsive automation with other Cloudinary features.

Resolution Switching

Switching an image’s resolution enables viewing of that image on different devices. Typically, you specify multiple versions of the image and display the one that is most appropriate to the user’s current display.

Before, you could specify only one source file with HTML’s <img> element for the browser. Now you can add more source images with hints in the srcset and size attributes to help the browser choose the right image.

“Optimise

Below is an example:

<img srcset="cute-cat-480w.jpg 480w,cute-cat-800w.jpg 800w"
  sizes="(max-width: 600px) 480px,800px"
  src="cute-cat-800w.jpg"
  alt="Cute cat sitting on the porch">

Both srcset and sizes contain a comma-separated list of values:

  • srcset specifies the absolute sizes of the images as choices for the browser.
    The syntax is as follows:

The image’s file name, a space, the image size with the w unit

The value of w denotes the intrinsic size of the image in storage—not pixels, which denote the size of the image as displayed on the screen.

  • sizes defines the media conditions, such as the screen width, and specifies the optimal image size to select for a specific media condition. Here’s a list of all the available media features.The syntax is as follows:The name of the media feature, a colon, the condition to look for, a space, the width the image fills if the media condition is true.

 

Setting srcset and sizes with max-width triggers the following browser process:

  1. The browser looks up the width of the device.
  2. The browser identifies the first media condition in the sizes attribute that is true.
  3. The browser looks up the slot size specified in the media query.
  4. The browser loads an image with the same size, if available; and, if not, the first image that is larger than the selected slot size.

Here are the related scenarios:

  • If a user accesses the page with a viewport of width 500, because the media condition is true (width of less than 600), the browser loads the image with size 480w, saving . significant bandwidth for users with smaller screens.
  • If a user accesses the page with a viewport of width 700, the browser loads the larger image of 800w.
  • If a user accesses the page with an old browser that does not support media queries, the browser complies with the settings of the regular src attribute and loads the 800w image—regardless of screen size.

Image-Format Switching

New image formats like WebP, replete with small file size and high quality, are widely used and supported by all modern browsers. Google’s website-performance guidelines now explicitly require that websites adopt modern image formats when possible.

To switch image format according to browser capabilities, add the <picture> element. The following example shows various image formats to switch to, depending on the MIME type supported by the browser.

<picture>
  <source type="image/svg+xml" srcset="car.svg">
  <source type="image/webp" srcset="car.webp">
  <img src="car.png">
</picture>

The first option is the most lightweight SVG. If the browser does not accept it, the next option is WebP. And if the browser rejects both, it loads the traditional PNG format.

As in the previous code examples, a comma-separated list of the srcset and sizes properties denotes the multiple image sizes for each format.

How Do You Create Responsive Images in HTML With Cloudinary?

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload images and apply built-in effects, filters, and modifications. You can also create image effects that are difficult or impossible to produce with just CSS.

Cloudinary makes it simple to deliver responsive images by doing the following:

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better manage responsive images in HTML:

  1. Avoid serving oversized images with client-side scaling
    Always avoid serving high-resolution images and then scaling them down on the client side with CSS. This unnecessarily increases load times. Instead, use the srcset and sizes attributes to serve the smallest image needed based on the viewport size.
  2. Precompress images for faster delivery
    Even before using a platform like Cloudinary, precompress images using tools like ImageOptim or TinyPNG. This ensures that your base image files are as small as possible, speeding up download times even before any responsive techniques are applied.
  3. Use responsive images for in-article images, not just for layout or backgrounds
    Many developers focus on responsive images in headers or banners but forget about inline content images. These images can also benefit from using srcset to improve performance, particularly on mobile where large inline images can slow down content loading.
  4. Test for device pixel ratio (DPR) on high-DPI displays
    On retina or high-DPI displays, your images may look pixelated even if you have the right size for the screen. Test with device pixel ratios and provide 2x or 3x images where needed using srcset to ensure crisp visuals on such devices.
  5. Use image CDNs for faster global delivery
    Use a CDN (like Cloudinary or Fastly) that is optimized for image delivery, not just a standard CDN. Image CDNs are designed to serve optimized versions of images and have specialized features like format conversion, which is essential for fast performance across different devices and browsers.
  6. Lazy load below-the-fold images
    Incorporate lazy loading for all images that are initially off-screen using the loading="lazy" attribute. This technique is especially useful for mobile users, as it reduces the amount of data transferred during the first page load.
  7. Include width and height attributes to prevent layout shifts
    Always include width and height attributes in your img tags to avoid layout shifts. Even when using responsive images with srcset, these attributes ensure that the browser allocates the correct space for the image before it’s loaded, helping avoid cumulative layout shift (CLS) issues.
  8. Automate format switching based on browser capabilities
    Use the picture element to serve modern formats like WebP or AVIF to browsers that support them, while providing fallback formats like PNG or JPEG. This allows you to optimize image delivery for newer browsers while ensuring compatibility with older ones.
  9. Monitor image performance with real user metrics (RUM)
    Utilize real user metrics tools like Google Lighthouse or SpeedCurve to monitor how responsive images impact performance for users across different devices. This data can help you fine-tune image sizes, formats, and delivery methods based on actual user conditions.
  10. Combine art direction with responsive images
    When using the picture element, go beyond resolution switching by applying art direction. Serve different compositions of an image for various breakpoints, ensuring that the most important part of the image is highlighted for each screen size, enhancing the user experience.

These techniques will help you maximize the performance and responsiveness of images in HTML, ensuring better user experiences across devices.

Last updated: Oct 1, 2024