Next.js
/Advanced
Responsive Images
Definition
Using the `sizes` attribute or the `fill` prop to handle images whose physical size on the screen changes across different breakpoints (mobile vs desktop).
Explain Like I'm New
If you hardcode `width={500}`, the image is always 500px wide. But what if you want an image that stretches to fill the entire width of the user's screen? You use the `fill` property, and you tell Next.js the `sizes` so it knows exactly what file sizes to generate.
Real World Example
A Hero Banner at the top of a webpage. It needs to be 400px wide on a phone, and 2000px wide on a 4K monitor. The `fill` prop combined with CSS `object-cover` makes this effortless.
Common Use Cases
- •Hero images
- •Fluid grids
- •Background images
Interactive Example
import Image from 'next/image'; export default function HeroBanner() { return ( // 1. The parent MUST be relative and have a defined height/width! <div className="relative w-full h-96"> {/* 2. The Image uses 'fill' to perfectly match the parent box */} <Image src="/massive-background.jpg" alt="Hero" fill // 3. object-cover prevents the image from looking squished/distorted className="object-cover" // 4. 'sizes' tells the server EXACTLY what sizes to generate to save bandwidth sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" /> </div> ); }
Interview Questions
basic
- If you use the `fill` property on an `<Image>`, do you still need to provide `width` and `height` properties?
intermediate
- If you use `fill`, what CSS position class MUST be applied to the parent `<div>` wrapping the image?