Next.js Image Tag - How to fill the entire width of the parent container & maintain the image's aspect ratio

When using the Next.js Image tag, you must add the width and height attributes, or layout="fill" or your application will not compile. You have to add something like:

<Image
  src={"/images/me.png"}
  alt="an image of the author"
  width={50}
  height={50} 
/>

This is all well and good but what if your image is coming from some external source and you want to fill the entire width and keep the image's aspect ratio? Essentially, you want to set width: 100% and height: auto. With a regular image tag, this is easily done, but with the Next.js Image tag, many developers have struggled with it.

After crawling through many forums, arnovanstaden posted a solution on the Next.js github page.

You must add a container div around your Image tag, and add the following styles.

<div className="imageContainer">
        <Image src={somePath} 
           layout="fill" 
           className="image" 
        />
</div>
.imageContainer {
        width: 100%;

        >span {
            position: unset !important;
        }

        .image {
            object-fit: contain;
            width: 100% !important;
            position: relative !important;
            height: unset !important;
        }
    }

Note: You may need to change span to div. Use the dev tools in your browser to see how it is rendering.

And there you have it!


Image of the Author, Ryan Carmody

About the Author

Open for work

Hi, I'm Ryan from Adelaide, South Australia.

I'm a web developer and computer science tutor. I also rock climb, play wheelchair basketball and brew beer.

Check out some of the games I made

Smug Chicken

Smug Chicken

The daily AI art word game.

Searchle

Searchle

How does google autocomplete this search?

WhereTaken

WhereTaken

Guess the country from a photo.

Retro Snake Game

Retro Snake

Eat the food but don't hit the walls or your own body!