Why a Small sizes Value Shrinks the Image Itself, and the CSS Line to Add When width and height Attributes Stretch It
The day I added responsive images, one artwork shrank and another stretched sideways. How sizes sets the displayed size, the one CSS line for width and height attributes, and how to work out sizes for tall art in a frame, with numbers and a check script.
It was late July, and I was running PageSpeed on an artist's official site I build and maintain. Under "Properly size images" I saw the names of artworks I knew well. On phones, a painting that only ever filled a slot of roughly 380×507 was being served at its full 1108×1477. The wasted transfer came to 734 KiB.
I thought I knew the fix. Generate a few WebP widths, add srcset and sizes, done. I worked through it with an agent, shipped it, and opened the live page. The artwork at the top had become noticeably smaller. To lock the aspect ratio I then added width and height attributes, and then the hero image stretched sideways. Two breakages, two different causes, one afternoon.
Both had the same root. A value I treated as "which file should load" was also deciding "how big it should look". Below are the numbers from reproducing both, the way I decide these values now, and the small script I run before every release.
sizes decides the displayed size, not only the file
sizes tells the browser, ahead of layout, roughly how wide the image will be. From that and the screen density the browser chooses a candidate from srcset. Most explanations stop there.
What they rarely mention is the next step. An image chosen from a w-descriptor srcset takes the width you declared in sizes as its own intrinsic width, not the pixel width of the file. If your CSS never sets width on that image, it is drawn at that intrinsic width. Underestimate sizes, and you do not just download a smaller file; the picture on screen shrinks.
My layout held artwork in check with max-height: 74vh and percentage max-width, and never set width. I reasoned that CSS already capped the size, so a conservative sizes would be harmless. That reasoning was the first breakage.
What I measured
I rebuilt the situation with Playwright's Chromium in headless mode. From a 1108×1477 image I generated 320, 480, 800 and 1108 WebP variants, and styled the page with nothing but max-height: 74vh; max-width: 90vw. Then I read the rendered box and currentSrc on a desktop-like viewport (1280px, 1x) and a phone-like one (390px, 3x).
Setup
Desktop 1280px, 1x
Phone 390px, 3x
A. sizes="200px" (conservative guess)
200×267 (320 file)
200×267 (800 file)
B. sizes="(max-width: 860px) 90vw, 900px"
444×592 (1108 file)
351×468 (1108 file)
C. width and height attributes only
1108×592 (stretched wide)
351×625 (stretched tall)
D. C plus width:auto; height:auto
444×592
351×468
In row A the CSS would allow 444px, yet the image stops at 200px. On the phone the browser correctly fetches the 800 file for the 3x screen, and still draws it at 200px. The download is right and only the appearance is wrong, so the network panel shows nothing unusual.
The other surprise: in row A, naturalWidth returned neither 320 nor 800, but 200. If you assume naturalWidth is the file's pixel width, your checking script will misread the page too. With srcset, you get the value already divided by the chosen density.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Before adding srcset, you can pick a sizes value from your own layout that never shrinks the image, knowing that sizes decides the displayed size as well as which file loads
✦You can prevent the sideways stretch that appears the moment you add width and height attributes with one CSS line before release, instead of hunting for the cause afterwards
✦Even where tall artwork sits inside a fixed frame with object-fit contain, you can work out sizes from the width the art actually occupies and make the browser pick your small variants
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
I settled on one rule. Declare sizes a little larger than the widest the image can ever be shown, and let CSS max-* decide the final size.
<!-- Before: a conservative guess, so the image stopped at 200px --><img src="/works/art-1108.webp" srcset="/works/art-320.webp 320w, /works/art-480.webp 480w, /works/art-800.webp 800w, /works/art-1108.webp 1108w" sizes="200px" alt="Title of the work"><!-- After: one step above the widest display (90vw on phones, about 444px on desktop) --><img src="/works/art-1108.webp" srcset="/works/art-320.webp 320w, /works/art-480.webp 480w, /works/art-800.webp 800w, /works/art-1108.webp 1108w" sizes="(max-width: 860px) 90vw, 900px" alt="Title of the work">
As the table shows, a generous value can fetch the 1108 file for a 444px slot on desktop. That one-step-too-large download is the price, and it is still far lighter than sending the original to everyone. What it buys is that nothing shrinks. I would rather read a little more than show the art smaller than intended.
The alternative is to fix width in CSS and match sizes to it exactly. On a site where artworks come in every aspect ratio, a fixed width pushes tall pieces off the screen. Keeping the height-capped layout and matching sizes precisely means deriving it from viewport height and aspect ratio, which becomes a formula nobody else can read later.
The one line for stretched images
The second breakage came from width and height. Those attributes exist so the aspect ratio is known before the image decodes, which prevents layout shift. But HTML attributes also act as CSS width and height.
Add them to an image that is only limited by max-height: 74vh, and the height stops at 74vh while the width stays at the attribute's 1108px. That is row C: 1108×592 on desktop, a ratio that looks nothing like the painting.
The fix is a single CSS declaration.
/* Keep the attributes, but let CSS max-* decide the size */.hero img,.works img { width: auto; height: auto; /* the attributes now only feed aspect-ratio */ max-height: 74vh; max-width: 90vw;}/* Images that fill a frame with contain never look distorted, so attributes alone are fine */.frame img { width: 100%; height: 100%; object-fit: contain;}
With width: auto; height: auto, the attributes only feed the browser's default aspect-ratio. The ratio is known before decoding, and max-height still sets the size, exactly as before. Row D confirms it: width and height return to the same proportions as rows A and B.
Images fitted into a box with object-fit: contain did not need the line at all, since a distorted box does not distort the picture inside it. The breakage only hits images whose CSS sets neither width nor height, just upper limits.
For tall art in a frame, write sizes from the art, not the frame
Where artworks sit in a 4:5 frame with object-fit: contain, a different waste remained. The taller the piece, the narrower the area it actually paints. In production, a 447×1800 work was drawn only about 106px wide inside a 306px frame.
Declare the frame width, sizes="306px", and a 3x phone concludes it needs about 918px, so it takes the original. The 240 and 320 variants you prepared are never chosen. In my reproduction at 390px and 3x, sizes="306px" picked the 447 original; switching to sizes="95px", computed by the function below, picked the 320 file. On a 1x desktop it picks 240.
The calculation fits in a few lines.
// Pass the width the art really occupies when it is fitted inside a frame// frameW: frame width in px, frameRatio: frame height / width (1.25 for 4:5)// imgW, imgH: original size of the artworkexport function framedSizes(frameW, frameRatio, imgW, imgH) { const aspect = imgW / imgH; // smaller for tall pieces const scale = Math.min(1, aspect * frameRatio); // share of the frame width used return `${Math.ceil(frameW * scale)}px`;}// A 447x1800 work in a 306px 4:5 frameconsole.log(framedSizes(306, 1.25, 447, 1800)); // "95px"// Wide work is limited by the frame width, so it gets the full widthconsole.log(framedSizes(306, 1.25, 1600, 1200)); // "306px"
The real frame has padding bands, so the inner ratio was 1.218 rather than 1.25. Measure the inside of your own frame before fixing the factor. Because the box size comes from the attributes and CSS, tightening sizes this far does not move the layout at all. The shrinking problem from earlier cannot happen here, since the frame, not the image, decides the size.
One more catch: tall pieces have small original widths, so a variant script that builds steps at 480, 800 and up never produced anything small for them. The calculation only paid off after I made the script always emit 240 and 320 steps.
When the column count changes, sizes must change with it
On another artist's site, the work list could switch between one and two columns. Two was the default, but sizes still described the one-column layout, so desktop browsers fetched the 800 file for a 313px slot. After splitting sizes into one-column and two-column values, the image transfer for a full scroll on desktop dropped from 10.6MB to 5.3MB.
On the same site, the large figure on each work page needed about 1,030px on a 3x phone, but the steps jumped from 800 straight to 1600. Adding a 1200 step took each image from 773KB to 512KB. Even a correct sizes still lands one step up when the steps are coarse.
I left the cover image at sizes="85vw", though. When I rewrote it as a height-based formula, the framework's automatic preload and the img itself chose different variants, and the same picture downloaded twice. How far to chase precision is always weighed against side effects like that.
eager plus srcset adds preloads to the head
One more slowdown appeared after adding srcset. A slideshow loaded the previous and next works with loading="eager", and the built HTML opened with four <link rel="preload" as="image"> tags at the top of <head>. React's server rendering was inserting preloads for eager images that carry srcset.
Those artwork preloads landed ahead of the font preload, and on a throttled run FCP worsened from 2.7 seconds to 3.7 seconds. Keeping eager for the single image needed on first paint, and moving the neighbours back to lazy, restored it.
Checking is a matter of counting in the built HTML.
#!/usr/bin/env bash# usage: bash check_preload.sh out/index.htmlset -euo pipefailhtml="${1:?pass the path to the HTML file}"img_preload=$(grep -o '<link rel="preload" as="image"' "$html" | wc -l | tr -d ' ')font_pos=$(grep -bo 'rel="preload"[^>]*woff2' "$html" | head -1 | cut -d: -f1 || true)echo "image preloads: ${img_preload}"echo "font preload at byte: ${font_pos:-none}"# One image preload at most. More than one means too many eager srcset imagesif [ "$img_preload" -gt 1 ]; then echo "NG: too many eager srcset images" exit 1fi
The font preload also sinks when CSS is inlined into the head, so I check that it sits within the first 10,000 bytes while I am there.
The check I run before every release
The breakages above come in two kinds: the network is right but the picture looks wrong, or the picture looks right but too much is downloaded. You can see the first kind and only measure the second, so I wrote a small script that reads every image.
# usage: python3 audit_img.py <URL> [width] [DPR]import sysfrom playwright.sync_api import sync_playwrightJS = """async () => { // scroll to the bottom and back so lazy images start loading for (let y = 0; y < document.body.scrollHeight; y += innerHeight) { scrollTo(0, y); await new Promise(r => setTimeout(r, 150)); } scrollTo(0, 0); const out = []; for (const img of document.images) { const shown = (img.currentSrc || img.src).split("/").pop(); const box = img.getBoundingClientRect(); const cs = getComputedStyle(img); // naturalWidth is corrected by the w descriptor, so reload the file to get its pixels const probe = new Image(); probe.src = img.currentSrc || img.src; try { await probe.decode(); } catch (e) {} // to see whether sizes shrinks the image, place a "twin" without srcset next to it. // removing srcset from the same element kept the old density in Chromium let freeW = box.width; if (img.srcset && cs.objectFit === 'fill') { const twin = document.createElement('img'); twin.className = img.className; twin.style.cssText = img.style.cssText + ';visibility:hidden'; for (const a of ['width', 'height']) if (img.hasAttribute(a)) twin.setAttribute(a, img.getAttribute(a)); twin.src = img.getAttribute('src') || img.currentSrc; // fallback, usually the original img.after(twin); try { await twin.decode(); } catch (e) {} freeW = twin.getBoundingClientRect().width; twin.remove(); } out.push({ freeW, src: shown, w: box.width, h: box.height, natural: img.naturalWidth, fileW: probe.naturalWidth, fileH: probe.naturalHeight, fit: cs.objectFit, sizes: img.sizes, dpr: devicePixelRatio, }); } return out;}"""def judge(r): issues = [] if r["w"] == 0: return ["rendered width 0 (not measurable, recheck on the real page)"] # 1. the twin without srcset renders larger, so sizes is setting the width if r["sizes"] and r["freeW"] > r["w"] + 1: issues.append(f"sizes shrinks it ({r['w']:.0f}px, could be {r['freeW']:.0f}px)") # 2. aspect ratio drifts without object-fit (width/height attributes acting as CSS) if r["fit"] == "fill" and r["fileW"] and r["fileH"]: drift = abs((r["w"] / r["h"]) / (r["fileW"] / r["fileH"]) - 1) if drift > 0.02: issues.append(f"aspect ratio off by {drift:.0%}") # 3. more than 1.6x the pixels actually needed need = r["w"] * r["dpr"] if r["fit"] == "contain" and r["fileW"] and r["fileH"]: # for art fitted in a frame, estimate from the painted width need = min(r["w"], r["h"] * r["fileW"] / r["fileH"]) * r["dpr"] if r["fileW"] > need * 1.6: issues.append(f"oversized {r['fileW']}px (needs about {need:.0f}px)") return issuesdef main(): url = sys.argv[1] width = int(sys.argv[2]) if len(sys.argv) > 2 else 390 dpr = float(sys.argv[3]) if len(sys.argv) > 3 else 3 with sync_playwright() as p: b = p.chromium.launch() page = b.new_page(viewport={"width": width, "height": 844}, device_scale_factor=dpr) page.goto(url, wait_until="load") rows = page.evaluate(JS) b.close() print(f"== {url} @ {width}px x{dpr}") for r in rows: issues = judge(r) mark = "NG" if issues else "OK" print(f"{mark} {r['src']} {r['w']:.0f}x{r['h']:.0f} file={r['fileW']}px", " / ".join(issues))if __name__ == "__main__": main()
Run against the reproduction page at 390px and 3x, row A reports that sizes shrinks it from a possible 351px to 200px, and row C reports an aspect ratio off by 25%. Rows B and D pass.
I tripped twice while writing it. First, I tried removing srcset from the image under test and measuring again. Chromium kept the previously chosen density, so even after reloading the 1108 file the image was drawn at an odd 277px. That is why the script now compares against a separate twin.
Second, when a later img on the same page pointed straight at the original file, the earlier srcset image switched to that original too. I confirmed it with three tiny pages: only the page with the original image placed after it made the sizes="200px" image swap to the 1108 file. The twin loads originals as well, so I treat the "oversized" flag as a hint and recheck suspicious rows on a page containing just that image. Inside flex or grid containers the twin shares the row width, so an NG there also needs a look by eye.
What I now put in the instructions when an agent adds srcset
The first breakage was not the agent's mistake. Writing sizes as the width of the visible slot is the textbook approach. What I had not said was that my site sets no width and relies only on upper limits.
Now, whenever I hand over image work, these assumptions go at the top of the instructions.
Image assumptions specific to this site- Artwork images have no CSS width; size is capped only by max-height / max-width- So write sizes one step larger than the widest display (a smaller value shrinks the image)- When adding width / height attributes, also apply width:auto; height:auto in CSS to that img- For images fitted in a frame with object-fit: contain, write sizes from the painted width, not the frame- Use loading="eager" only for the first-paint image; confirm the built <head> has one image preload- Never batch-replace sizes values with a regex (media query numbers change too)- When done, run audit_img.py at 390px 3x and 1280px 1x and report every NG row
The words "specific to this site" are the point. An agent knows the general theory of responsive images better than I do. What it cannot know is where I broke things before and why the layout is built this way.
Where I draw the line now
Breaking it twice finally showed me how to divide the work. Let sizes choose the file, and let CSS choose the look. Ask sizes to tune appearance and the image shrinks; let the attributes set the size and it stretches. I simply keep each value in its own job.
If you are about to touch images, I would start by checking, image by image, whether your CSS sets the width or only caps it. Any image that is only capped is a place where sizes should be written generously. As an indie developer, I am often the only person who knows these assumptions about my sites, which is why I now write them into the instructions rather than keep them in my head.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.