<Image> (Advanced)

Fluid responsive images using the fill prop.

Next.js3 min readConcept 50 of 65

The Fill Prop

If you don't know the dimensions of an image (e.g., in a fluid, responsive CSS Grid), you can bypass the width and height requirements by using the fill prop.

When fill is true, Next.js injects CSS to make the image automatically expand to fill its parent container.

The Absolute Positioning Trap

The fill prop works by applying position: absolute and height: 100%, width: 100% to the image.

In CSS, absolute elements expand until they hit a relative parent.

If you forget to add position: relative to the parent <div>, the image will expand past your layout and cover the entire browser window.

Implementation

1. Add position: relative to the parent.

2. Add <Image fill src="..." />.

3. Add className="object-cover" so the image maintains its aspect ratio instead of squishing and distort.

4. Add the sizes prop (e.g. sizes="(max-width: 768px) 100vw, 50vw") to prevent Next.js from downloading unnecessarily massive images on mobile devices.

Fill vs Explicit Dimensions

Examine the syntax difference between a hardcoded, explicitly dimensioned image and a fluid, responsive image using the fill prop.

Explicit Dimensions

ExplicitProfile.tsx
import Image from 'next/image';
export default function Profile() {
return (
// Dimensions must be known upfront
<Image
src="https://cms.com/avatar.jpg"
alt="User Avatar"
width={500}
height={500}
/>
);
}

Fluid Container (fill)

FluidGallery.tsx
import Image from 'next/image';
export default function Gallery() {
return (
// The parent MUST be relative
<div className="relative w-full aspect-video">
<Image
src="https://cms.com/banner.jpg"
alt="Fluid Banner"
fill
className="object-cover"
sizes="(max-width: 768px) 100vw, 50vw"
/>
</div>
);
}

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What CSS property is absolutely required on the parent container when using the Next.js `<Image fill />` prop?

Remember this

  • Use fill when you don't know the exact dimensions.
  • The parent container MUST have position: relative.
  • Apply object-cover to prevent the image from distorting.
  • Always provide a sizes prop when using fill to optimize mobile downloads.

Done with this concept?

Mark it complete to track your progress. No login needed.