Next.js Discord

Discord Forum

Render next/image in full height, responsively.

Answered
Pacific anchoveta posted this in #help-forum
Open in Discord
Avatar
Pacific anchovetaOP
Hi, everyone.

I struggle to find the right/correct way of rendering the next/image component in full height (100vh) and respecting the aspect ratio, on all screen sizes.

I want to render a modal when the user clicks on an image, and I want this modal to render full screen height. So, the Image needs to "fill" it's parent container height, but respect the aspect ratio, so that it will leave some space in the width, alternatively crop the top if the image is wide enough to not demand full height.

I fetch the image from Sanity, so I got metadata available to me, such as aspect ratio, original width and height.

For the time being I can't find any other solution than setting the parent
relative**, but then I need to specify the width and height of the container as well it seems. I don't think this will work when I want this to be repsonsive on different screen sizes.

Anyone got some tips for me?

All help appreciated.

(see screenshot for current configuration)
Image
Answered by not-milo.tsx
You can override the width and height values using tailwind. You need to add a className to the image itself and control its dimensions that way. For example:

import Image from "next/image";

export default function Home() {
  return (
    <div className="h-screen w-screen fixed top-0">
      <Image
        src="/assets/images/aditya-chinchure-5nuRRWZ96eI-unsplash.jpg"
        alt="A view of Vancouver with mountains in the background"
        width={500}
        height={500}
        quality={100}
        sizes="100vw"
        className="bg-slate-600 h-full w-full object-contain"
      />
    </div>
  );
}
View full answer

6 Replies

Avatar
You can override the width and height values using tailwind. You need to add a className to the image itself and control its dimensions that way. For example:

import Image from "next/image";

export default function Home() {
  return (
    <div className="h-screen w-screen fixed top-0">
      <Image
        src="/assets/images/aditya-chinchure-5nuRRWZ96eI-unsplash.jpg"
        alt="A view of Vancouver with mountains in the background"
        width={500}
        height={500}
        quality={100}
        sizes="100vw"
        className="bg-slate-600 h-full w-full object-contain"
      />
    </div>
  );
}
Answer
Avatar
The result would be this
Image
Avatar
Pacific anchovetaOP
That worked, thanks 🙏
Avatar
Sun bear
I was wondering this the other day. So does this mean that we can use any value for the width and the height?
Avatar
yes
Avatar
Sun bear
Great. Thank you.