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>
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; }
Top comments (8)
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.
This is the cleaner solution.
Nice!
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...
Thanks bro....
Thank you so much for this! Was struggling to get it working before your post.
it worked.
can you please tell me how you arrived at this solution .
would be very interesting to know.
thanks a bunch.
cheers.
sweat and tears 😆 .. and github issue github.com/vercel/next.js/discussi...