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!
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.