Skip to content

Instantly share code, notes, and snippets.

@MadaShindeInai
Last active December 17, 2023 13:11
Show Gist options
  • Save MadaShindeInai/5e70a2968171e75d9dc395120dba8d7c to your computer and use it in GitHub Desktop.
Save MadaShindeInai/5e70a2968171e75d9dc395120dba8d7c to your computer and use it in GitHub Desktop.
Next Image

Next Image in Responsive way:

1. Container for image with "relative" and defined width/height.

2. Fill

AFAIK: srcset created by Next depending on sizes, so you need to specify sizes in strict width descriptiors.

The sizes attribute in the img element is used to define the width of the image for different viewport sizes. It is often used in conjunction with the srcset attribute for responsive images. The sizes attribute takes a series of values separated by commas. Each value consists of a media condition followed by a corresponding width descriptor.
The width descriptors represent the intended display size of the image for a given media condition. The most common width descriptor is vw, which stands for viewport width. However, other units are also available. The following units can be used for image sizes in the sizes attribute:

  1. vw (Viewport Width): Represents a percentage of the viewport width. For example, 100vw means the image should be displayed at 100% of the viewport width.

    <img src="example.jpg" sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 25vw" srcset="...">
  2. px (Pixels): Represents a fixed number of pixels.

    <img src="example.jpg" sizes="(max-width: 600px) 300px, (max-width: 1200px) 600px, 900px" srcset="...">
  3. em (Relative to Font Size): Represents a size relative to the font size of the root element.

    <img src="example.jpg" sizes="(max-width: 600px) 20em, (max-width: 1200px) 40em, 60em" srcset="...">
  4. rem (Relative to Root Font Size): Represents a size relative to the font size of the root element.

    <img src="example.jpg" sizes="(max-width: 600px) 20rem, (max-width: 1200px) 40rem, 60rem" srcset="...">

It's important to note that the sizes attribute is used to provide hints to the browser about the intended display size of the image. The browser uses this information to decide which image source to download from the srcset based on the current viewport size. The actual rendering size can be further controlled with CSS.

sizes="(min-width: 640px) 192px, (min-width: 1100px) 256px, 128px"

If the viewport width is at least 1100 pixels: 256 pixels
If the viewport width is at least 640 pixels but less than 1100 pixels: 192 pixels
If the viewport width is less than 640 pixels: 128 pixels (fallback size)

4. Add className="object-cover object-center" to Image to keep proportions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment