Responsive image sizes
Scope: Next.js 16.x candidate, App Router, Cache Components disabled, TypeScript. Source walkthroughs and expected outcomes; no framework build or browser execution has been verified.
What you will learn
- Describe viewport-dependent sizes
- Avoid incorrect size hints
BookCard.tsx — complete card component
import Image from 'next/image';import Link from 'next/link';import type { PublicBook } from '../../lib/public-book';import styles from './catalog.module.css';export default function BookCard({ book }: { book: PublicBook }) { return <article className={styles.card}> <div className={styles.cover}><Image src={book.cover} alt="" fill sizes="(max-width: 306px) calc(100vw - 66px), 240px" style={{ objectFit: 'contain' }} /></div> <h2><Link href={`/catalog/${book.slug}`}>{book.title}</Link></h2> <p>${book.price}</p> </article>;}The image fills its wrapper without cropping, and its visible title remains a link.
How it works
With fill, the image occupies its positioned parent, which must have a useful size. In the fixture, the cover wrapper has a 2:3 aspect ratio and a 240px maximum width. At narrow widths the combined main and card padding plus border consumes approximately 66px, so the hint uses viewport minus that space below 306px. At wider viewports each card can accommodate the cap. objectFit: contain keeps the full artwork visible; cover may crop it. Browser density, available candidates and heuristics still determine the downloaded resource.
catalog.module.css — cover wrapper
.cover { position: relative; width: min(100%, 240px); aspect-ratio: 2 / 3; }The wrapper establishes a nonzero containing box before the image loads.
Common mistake
Using fill with a parent that has no height can make the image invisible; omitting sizes can encourage an oversized candidate. A hint of 100vw is not appropriate for a small capped card at desktop widths.
Try it yourself
Change the maximum wrapper width to 180px. Recalculate the narrow threshold to 246px and update sizes. In an approved browser inspect rendered width and currentSrc; do not infer actual downloaded bytes from sizes alone.
Further reading
Next lesson: Image source policy and loaders.