Vanilla Breeze

data-responsive

Simplified responsive image API with auto-calculated sizes, srcset shorthand generation, and optional dev overlay showing the selected source.

Overview

The data-responsive attribute upscales native srcset and sizes with two features developers frequently get wrong: automatic sizes calculation from rendered layout width, and a compact shorthand for generating srcset from a list of widths.

How It Works

The enhancement does three things:

  1. Auto-sizes — A ResizeObserver measures the image’s rendered CSS pixel width and sets sizes to match. This ensures the browser always picks the closest source for the actual layout.
  2. Srcset shorthand — If data-responsive has a value (comma-separated widths), it generates srcset from the src by inserting -{width} before the file extension.
  3. Performance defaults — Sets loading="lazy" and decoding="async" if not already specified.

Srcset Shorthand

Instead of writing verbose srcset attributes, provide the widths and the enhancement generates sources from your src filename:

The naming convention inserts -{width} before the extension. So photo.jpg with widths 400,800 produces photo-400.jpg 400w, photo-800.jpg 800w.

Attributes

Attribute Value Description
data-responsive empty or widths Enable auto-sizes. Optionally provide comma-separated widths (e.g. "400,800,1200") to generate srcset.
data-responsive-debug boolean Show a dev overlay badge on the image displaying the current source filename and natural width.

Dev Overlay

Add data-responsive-debug to see which source the browser selected. The overlay shows the filename and natural pixel width, updating on each load.

Remove the data-responsive-debug attribute for production.

Performance Defaults

The enhancement auto-sets these attributes if not already present:

Attribute Default Override
loading lazy Set loading="eager" for above-the-fold images.
decoding async Set decoding="sync" if you need synchronous decode.

Examples

Auto-sizes only

When you already have a correct srcset but want auto-calculated sizes:

Full shorthand

Let the enhancement build everything from a single src:

Above-the-fold hero

Override loading for critical images:

How Sizes Auto-Calculation Works

The enhancement uses a ResizeObserver to measure the image’s rendered width in CSS pixels. As the layout changes (viewport resize, container queries), the observer updates sizes so the browser can make optimal source selections.

This replaces manually-written sizes like (max-width: 600px) 100vw, 50vw with an accurate measurement of the actual layout. The browser’s built-in sizes="auto" proposal works similarly but has limited support — this enhancement provides the same behavior in all modern browsers.