Responsive Images with srcset in Eleventy

A single 2,400-pixel JPEG served to every device is the most common image problem on Eleventy sites. Phones download four times the pixels they can show, LCP suffers, and the page weight report fills with images. Responsive images fix this by giving the browser a list of widths in srcset and a description of the display size in sizes, so it can choose the smallest file that still looks sharp.

Eleventy leaves images alone by default, which is why the official @11ty/eleventy-img package exists. This guide sets it up as a transform that upgrades every <img> in the output, chooses widths and sizes that match the layout, and keeps builds fast with caching. It sits alongside the Astro material in Image Optimization Pipelines in Astro, because the principles are identical and only the tooling differs.

Prerequisites

  • Eleventy 3.x and Node.js 20 or later.
  • @11ty/eleventy-img 5 or later: npm install @11ty/eleventy-img.
  • Source images stored in the repository, at least as wide as their largest display size at 2x density.

How the Browser Chooses a Candidate

srcset lists candidate files with their intrinsic widths. sizes tells the browser how wide the image will be displayed, before any CSS has loaded. The browser multiplies that display width by the device pixel ratio and picks the smallest candidate that covers it.

How the browser picks a srcset candidate Candidates are 400, 800, 1200 and 1600 pixels wide. A phone with a 360 pixel slot at 3x density needs 1080 pixels and picks the 1200 file. A laptop with a 720 pixel slot at 1x needs 720 and picks 800. A desktop with a 720 pixel slot at 2x needs 1440 and picks 1600. slot width × pixel ratio → smallest covering file Candidates 400w 800w 1200w 1600w Phone: 360 px slot × 3 needs 1080 1200w Laptop: 720 px slot × 1 needs 720 ↑ 800w Desktop: 720 px slot × 2 needs 1440 1600w without sizes the browser assumes 100vw and over-fetches on wide screens
The browser can only choose well if sizes describes the real layout.

If sizes is missing, the browser assumes the image fills the viewport. On a desktop with a 1,920-pixel window and a 720-pixel content column, it would fetch the 1,600 or larger file for a slot that needs 720 — the single most common reason responsive images still over-fetch.

Setting Up the Transform

eleventy-img 5 includes eleventyImageTransformPlugin, which runs after templates render and rewrites every <img> in the HTML. That covers Markdown images, Nunjucks templates and anything a shortcode emits, with one configuration:

// eleventy.config.js
import { eleventyImageTransformPlugin } from '@11ty/eleventy-img';

export default function (eleventyConfig) {
  eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
    formats: ['avif', 'webp', 'jpeg'],
    widths: [400, 800, 1200, 1600],
    urlPath: '/img/',
    outputDir: './_site/img/',
    htmlOptions: {
      imgAttributes: {
        loading: 'lazy',
        decoding: 'async',
        sizes: '(min-width: 768px) 720px, calc(100vw - 32px)',
      },
      pictureAttributes: {},
    },
  });
}

The output for each image is a <picture> element with one <source> per modern format and an <img> fallback carrying width, height, srcset and the attributes above. The intrinsic width and height are what prevent layout shift while the image loads.

Choosing Widths and Formats

Pick widths from the layout, not from a generic list. Work out the largest display width of each image type, multiply by two for high-density screens, and space three or four widths below that.

Bytes downloaded for one article hero on a phone Bars of bytes downloaded on a 360 pixel wide phone at 3x. The original 2400 pixel JPEG is 612 kilobytes. A 1200 pixel JPEG from srcset is 174 kilobytes. The same width as WebP is 118 kilobytes and as AVIF is 71 kilobytes. Hero image bytes on a 3x phone (KB) original JPEG, 2400w 612 JPEG, 1200w 174 WebP, 1200w 118 AVIF, 1200w 71 quality: AVIF 50, WebP 75, JPEG 78 — visually matched at 1:1
Right-sizing does most of the work; modern formats take the rest.

For formats, AVIF gives the smallest files and is supported by every current browser, WebP is the safety net for older Safari versions, and JPEG remains the universal fallback. AVIF encoding is slow, though, so on very large sites some teams generate only WebP and JPEG for images below the fold and reserve AVIF for heroes. See Serving AVIF with Fallbacks on Static Sites for quality settings.

Different Sizes for Different Images

One sizes value for the whole site is a start, but a thumbnail grid and a full-bleed hero need different descriptions. The transform respects attributes already on the <img>, so set sizes per image where the default is wrong. In Markdown, use the attributes plugin for markdown-it; in templates, write it inline:

<img src="./hero.jpg" alt="Build pipeline overview"
     sizes="100vw" loading="eager" fetchpriority="high"
     eleventy:widths="800,1600,2400">

The eleventy:widths attribute overrides the global widths for that image, and the transform strips it from the output. Note loading="eager" and fetchpriority="high" on the hero: the global loading="lazy" default must never apply to the LCP image, as explained in Lazy-Loading Images Without Hurting LCP.

Keeping Builds Fast

Encoding four widths in three formats is twelve files per source image. On a site with 3,000 images that is 36,000 encodes, and a cold build can take many minutes. Two mechanisms keep it manageable:

  1. Disk cache. eleventy-img hashes the source file and options, and skips work when the output already exists. Persist _site/img/ and the .cache directory between CI runs with actions/cache keyed on a hash of the image folder.
  2. Development mode. During eleventy --serve, the transform can serve images on request instead of encoding everything up front. Use transformOnRequest: process.env.ELEVENTY_RUN_MODE === 'serve' to keep local startup quick.

The cache key matters. Key it on a hash of the source image directory plus the Eleventy config file, so that changing widths or quality settings invalidates old outputs, while an unrelated content edit restores everything. Add a restore key without the hash suffix so a partial cache still helps when a few images change.

Image encoding time in CI with and without a restored cache Horizontal bars of CI time spent in image encoding on a 2800 image site. A cold build without cache takes 11 minutes. A pull request adding two images with the cache restored takes 20 seconds. A config change to widths invalidates the cache and takes 11 minutes again. Encoding step duration, 2,800 source images cold build, no cache 11 min PR adds 2 images, cache hit 20 s widths changed, key miss 11 min cache key: hash of src/img/** plus eleventy.config.js
A persisted cache turns image encoding from the slowest step into a rounding error.

On one 2,800-image documentation site, a cold CI build spent 11 minutes in image encoding; with the cache restored, the same step took 20 seconds for a typical pull request that added two images. More on caching strategy in Incremental Builds and Build Caching for SSGs.

Checking the Output

Test the result in the browser, not just in the HTML. In DevTools, select an image and read Current source in the properties panel, or hover the src in the network panel to see which candidate loaded. Resize the viewport and switch device emulation between 1x, 2x and 3x to confirm the choice changes as expected. Lighthouse's "Properly size images" audit flags images where the chosen file is much larger than the display size, which usually means sizes is wrong.

For a site-wide check, crawl the built output and compare each image's sizes against its rendered width in a headless browser at two or three viewport sizes. A small Playwright script that logs img.currentSrc and img.getBoundingClientRect().width for every image is enough to catch templates whose sizes drifted after a layout change.

Measured Impact

On an Eleventy marketing and docs site with 340 pages, switching from single JPEGs to the transform with four widths and three formats reduced median image bytes per page on mobile from 1.4 MB to 310 KB. Field LCP p75 on mobile fell from 3.1 to 2.2 seconds, mostly on article pages with hero images. Cached CI builds were four seconds slower than before; cold builds were nine minutes slower, which the team accepted because cold builds happened only on dependency upgrades.

Pitfalls & Rollback

  • Lazy-loading the hero. A global loading="lazy" delays the LCP image; override it per template.
  • Remote images. The transform downloads remote URLs at build time; cache them with a duration option or they are fetched on every build.
  • Upscaling. Widths larger than the source are skipped; check that sources are big enough.
  • Wrong sizes for grids. A three-column card grid needs a sizes for one column, not the page width.
  • Rollback: remove the plugin; images revert to their original single-file output.

Conclusion

Responsive images in Eleventy need three things: several encoded widths, a sizes value that describes the real layout, and caching so the encoding cost is paid once. @11ty/eleventy-img's transform plugin provides the first automatically for every <img>, per-image attributes handle the second, and a persisted cache handles the third. The result is the same as Astro's built-in <Image> component: phones download phone-sized files, and LCP improves on image-led pages.

FAQ

Which plugin should I use for responsive images in Eleventy?

The official @11ty/eleventy-img package. From version 5 it ships a transform plugin that rewrites every img element in your output HTML into a picture element with srcset, width and height, so Markdown images get the same treatment as template images.

How do I choose the sizes attribute?

Describe how wide the image is displayed at each breakpoint, using the same media queries as your CSS. For an image that fills a 720 pixel content column on desktop and the full width minus padding on phones, sizes could be (min-width 768px) 720px, calc(100vw - 32px).

Why are my Eleventy builds slow after adding eleventy-img?

Image encoding, especially AVIF, is CPU-heavy. eleventy-img caches outputs on disk and skips images whose source and options have not changed, so persist the output directory and .cache folder between CI runs to avoid re-encoding every image.

How many widths should I generate?

Three to five widths usually cover the useful range, for example 400, 800, 1200 and 1600 pixels for a content image. More widths add build time and storage with little gain because browsers pick the nearest larger candidate.