srcset.tips: Guide to Responsive Images

website·Indexed 32 days ago

https://srcset.tips

A technical guide focused on optimizing web images using the srcset attribute and <picture> element. Covers width and density descriptors, breakpoints, the difference between device and CSS pixels, and performance best practices for 2024, including the use of loading="lazy" and decoding="async".

Tokens
4.2K
Snippets
18
Records
29
Agent score
58%

What's inside srcset.tips

  1. Understand breakpoints in the context of responsive images

    A breakpoint is an arbitrary viewport width (measured in CSS pixels, not device pixels) where the page layout changes. For srcset and sizes implementation, breakpoints determine when an image's container changes its sizing behavior (e.g., switching from filling the viewport to a fixed maximum width). While some small assets like logos may only need density descriptors, main content images are typically constrained by their container's width, which varies based on the breakpoint.
  2. Understand the difference between CSS pixels and device pixels

    In modern web development, CSS and HTML pixels (px) are not 1:1 mappings to physical device pixels. Instead, they map to multiple device or printer pixels based on the devicePixelRatio. For example, a high-density mobile screen may have a devicePixelRatio of 3.875, meaning one CSS pixel covers multiple physical pixels. On desktops, this ratio can be affected by OS-level display scaling (e.g., 150% scale results in a ratio of 1.5) or browser zoom levels.
  3. Calculate the sizes attribute using the easy method

    To simplify the sizes attribute for responsive images, identify two key values: the viewport width where the image container stops growing and the maximum width that container ever reaches.

    1. If the container grows with the viewport up to a certain width (e.g., 700px), use 100vw for that range.
    2. For any viewport wider than that point, use the fixed maximum width of the container (e.g., 800px).

    This manual calculation is necessary because browsers select the image URL from srcset before stylesheets are downloaded and applied.

    <!-- Example: Container stops growing at 700px and maxes out at 800px --> <img src="image.jpg" srcset="..." sizes="(max-width: 700px) 100vw, 800px" />

  4. Avoid absolute CSS units for responsive layouts

    Avoid using absolute units such as in, pc, pt, mm, cm, or Q. These units are defined based on CSS pixels and assume a standard 96dpi, which can lead to layout breakage when users adjust accessibility text size, zoom the browser, or rotate their devices. It is recommended to use units derived from font size (e.g., em, rem) or viewport/container dimensions (e.g., vw, vh, %).
  5. Use the <picture> element for responsive image optimization

    The <picture> element allows developers to provide multiple versions of an image, enabling the browser to select the most appropriate source based on specific conditions. This is essential for responsive web design and performance optimization in the following scenarios:

    • High-Density (Retina) Displays: Provide high-resolution images (e.g., 2x pixel density) to prevent blurriness on high-DPI screens.
    • Art Direction: Serve entirely different image crops or compositions based on the viewport (e.g., a close-up for mobile and a wide shot for desktop).
    • Aspect Ratio Changes: Switch between landscape and portrait versions of an image to fit different layout requirements.
    • Bandwidth Optimization: Serve smaller, lower-resolution files to mobile devices or users on slow connections to improve page load speed.
  6. Serve resolution-specific images using srcset density descriptors

    Use the srcset attribute on an <img> element with density descriptors (e.g., 1x, 2x, 3x) to provide different image resolutions based on the user's display pixel density. This ensures high-DPI displays (like Retina displays) receive high-resolution images while standard displays receive lower-resolution images, optimizing both performance and visual quality.

    Implementation requirements:

    1. Provide images in multiple resolutions.
    2. Define the srcset attribute with a comma-separated list of image URLs and their corresponding density descriptors.
    3. Include a src attribute as a fallback for browsers that do not support srcset.
    <img src="example-image-1x.jpg"
         srcset="example-image-1x.jpg 1x, example-image-2x.jpg 2x, example-image-3x.jpg 3x"
         alt="An example image">
  7. Determine image sizes using the simplified breakpoint method

    To define the sizes attribute for an image without over-calculating complex layout shifts, use a two-step approximation based on the image's container:

    1. Identify the viewport width where the image's container stops growing. For all viewport widths up to this point, the image typically occupies the full width of the viewport (100vw).
    2. Identify the maximum fixed width the container ever reaches on larger screens.

    Because browsers select the image URL from srcset before CSS is downloaded, these calculations must be explicitly provided in the HTML sizes attribute using CSS pixels.

    <!-- Example: Container stops growing at 700px and has a max-width of 800px --> <img src="image.jpg" srcset="..." sizes="(max-width: 700px) 100vw, 800px" />

  8. Serve resolution-dependent images using srcset density descriptors

    Use the srcset attribute with density descriptors (e.g., 1x, 2x, 3x) to provide different image resolutions based on the pixel density of the user's display. This allows high-DPI displays (like Retina displays) to receive high-resolution images while standard displays receive lower-resolution versions, optimizing both page performance and visual quality.

    Implementation requirements:

    1. Prepare images in multiple resolutions.
    2. Define the srcset attribute with a comma-separated list of image URLs and their corresponding density descriptors.
    3. Provide a src attribute as a fallback for browsers that do not support srcset.
    <img src="example-image-1x.jpg"
         srcset="example-image-1x.jpg 1x, example-image-2x.jpg 2x, example-image-3x.jpg 3x"
         alt="An example image">
  9. Measure website performance using Google Chrome Lighthouse

    Lighthouse is a built-in Chrome tool used to measure performance, accessibility, and other website quality metrics. To generate a performance report:

    1. Open Google Chrome and navigate to the target URL.
    2. Open Developer Tools using Ctrl+Shift+I (Windows/Linux) or Command+Option+I (macOS).
    3. Access the Lighthouse tool by clicking the 'Lighthouse' tab in the Developer Tools panel, or open the Command Menu (Ctrl+Shift+P / Command+Shift+P) and type 'Lighthouse' then select 'Generate report'.
    4. Configure the desired categories (e.g., Performance) in the Lighthouse dialog box and click 'Generate report'.
    5. Review the resulting scores and optimization recommendations to improve user experience and SEO rankings.
  10. Understand how browsers select images using width descriptors (w)

    When using the w descriptor in srcset, the browser selects an image based on the Device Pixel Ratio (DPR) and the viewport width. The process is as follows:

    1. Determine DPR: The browser identifies the device's pixel density (e.g., 1 for standard, 2+ for Retina).
    2. Calculate Effective Width: The browser multiplies the width descriptor (e.g., 400w) by the DPR to find the effective pixel width.
    3. Compare to Viewport: The browser compares these effective widths to the current viewport width and selects the smallest image that is greater than or equal to the required width.

    Example: For a viewport of 420px and a DPR of 1, the browser would skip a 400w image and select an 800w image.

    <img src="example-small.jpg" srcset="example-small.jpg 400w, example-medium.jpg 800w, example-large.jpg 1600w" alt="Example Image">
  11. Use the Density (x) descriptor for high-DPI displays

    The x descriptor in the srcset attribute specifies the pixel density of an image, representing the ratio of physical pixels to CSS pixels. This is used to serve higher-resolution versions of the same image to devices with high-density displays (e.g., Retina displays).
    <img src="small.jpg"
      srcset="small.jpg 1x,
              medium.jpg 2x,
              large.jpg 3x"
      alt="Example Image">
  12. Prevent layout shift by specifying image width and height

    Include width and height attributes directly in the HTML <img> tags. This allows the browser to reserve the correct amount of space for the image before it is fully downloaded, preventing content from jumping (layout shift) and reducing unnecessary reflows or repaints. This practice improves overall page performance and the user experience by reducing visual glitches during load.
    <img src="example.jpg" width="600" height="400" alt="Description of image">