next/image - Make image fill available space without specifying height or width

tanahmed

Tan Ahmed

Posted on April 13, 2021

next/image - Make image fill available space without specifying height or width

The Next.js Image component has built-in Lazyloading but forces you to specify a width & height. Yet most times you do not know this information beforehand. Nor do you want images to look squashed by providing the wrong width or height.

I discovered with a few lines of CSS you can get around this. Thus your images will fill all the available space in the div.

So wrap the component with an unset-img class and give the component itself the className custom-img. Note the layout mode must be set to "fill".

<div className="unset-img">
  <Image alt="Mountains" src="/project/pexels-photo.jpeg" layout="fill" className="custom-img"
   />
</div>
Enter fullscreen mode Exit fullscreen mode

Here is the CSS which overrides the next.js functionality.

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

.unset-img {
  width: 100%;
}
.unset-img > div {
  position: unset !important;
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
tanahmed
Tan Ahmed

Posted on April 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related