DEV Community

Tan Ahmed
Tan Ahmed

Posted on • Edited on

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

Top comments (8)

Collapse
 
osaxon profile image
osaxon

Hi all, I've had trouble with this and managed to get it working by using width height at 100% and objectFit property 'contain' all as props within the Image component.

          <Image
            src={Logo}
            width='100%'
            height='100%'
            objectFit='contain'
            alt='Brand logo'
          />
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stackpoet profile image
Kenya Sullivan

This is the cleaner solution.

Collapse
 
janjakubnanista profile image
Ján Jakub Naništa

Nice!

Collapse
 
deadcoder0904 profile image
Akshay Kadam (A2K)

Thank you, I have been struggling with making a full-bleed layout for 6+ months → stackoverflow.com/questions/647387...

Finally, I've found your solution that works perfectly → stackblitz.com/edit/nextjs-image-f...

Collapse
 
romeshjaya profile image
romesh-jaya

Thank you so much for this! Was struggling to get it working before your post.

Collapse
 
mrtechmaker profile image
Mr.techmaker

it worked.
can you please tell me how you arrived at this solution .

would be very interesting to know.

thanks a bunch.

cheers.

Collapse
 
fredericrous profile image
Frederic R. • Edited

sweat and tears 😆 .. and github issue github.com/vercel/next.js/discussi...

Collapse
 
ashwinmaurya profile image
Ashwin Maurya

Thanks bro....