How to use Image component in Next.js with unknown width and height

Yeah, you could use it with the layout=fill option you mentioned.

On this case, you’re gonna need to set an “aspect ratio” for your images

<div style={{ position: "relative", width: "100%", paddingBottom: "20%" }} >
  <Image
    alt="Image Alt"
    src="/image.jpg"
    layout="fill"
    objectFit="contain" // Scale your image down to fit into the container
  />
</div>

You can use objectFit="cover" too and it’ll scale your image up to fill all the container.

The downside of this approach is that is gonna be attached to the width you specify, it could be relative such as “100%” or absolute e.g. “10rem”, but there’s no way to set like an auto width and height based on the size of your image, or at least no yet.

Leave a Comment