#next image

1 messages · Page 1 of 1 (latest)

cunning monolith
#

dont inderstand how sizes works in next js

valid mulchBOT
#

Hi @cunning monolith. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, the sizes property is used in the next/image component to provide information about how wide the image will be at different breakpoints. It's a string, similar to a media query. The value of sizes will greatly affect performance for images using fill or which are styled to have a responsive size.

The sizes property serves two important purposes related to image performance:

  1. The value of sizes is used by the browser to determine which size of the image to download, from next/image's automatically generated srcset. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. The sizes property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify a sizes value in an image with the fill property, a default value of 100vw (full screen width) is used.

  2. The sizes property changes the behavior of the automatically generated srcset value. If no sizes value is present, a small srcset is generated, suitable for a fixed-size image (1x/2x/etc). If sizes is defined, a large srcset is generated, suitable for a responsive image (640w/750w/etc). If the sizes property includes sizes such as 50vw, which represent a percentage of the viewport width, then the srcset is trimmed to not include any values which are too small to ever be necessary.

Here's an example of how you might use the sizes property:

import Image from 'next/image'
 
export default function Page() {
 return (
 <div className="grid-element">
 <Image
 fill
 src="/example.png"
 sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
 />
 </div>
 )
}
#

In this example, the image will take up the full viewport width on screens up to 768 pixels wide, half the viewport width on screens up to 1200 pixels wide, and 33% of the viewport width on screens larger than that.

For more information, you can refer to the Next.js documentation on the sizes property (https://nextjs.org/docs/app/api-reference/components/image#sizes).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: