DEV Community

loading...

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

tanahmed profile image Tan Ahmed Updated on ・1 min read

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

Discussion (0)

pic
Editor guide