Using Nextjs Image component with different image sizes
Asked Answered
D

2

7

I am trying to use the Next.js Image component with images that all have unique sizes. Their example states the image will stretch to the parent div width and height. I've tried wrapping them but don't know how to accommodate dynamic image sizes. I want to have a set width and the height to adjust to each respective proportion. TIA.

Here is my code (the images are coming from an array) -- since I don't have a height set nothing renders on the page. If i use Tailwind's h-auto it still does not display:

<div className="w-screen h-screen">
  {allImages.allImages.map((image, i) => {
    return (
      <div className="relative w-100 md:w-5/6 lg:w-7/12" key={image}>
        <Image priority src={`/${image}`} layout="fill" objectFit="cover" />
      </div>
  )})}
</div>
Dissolution answered 30/4, 2021 at 1:56 Comment(0)
I
2

I found a solution in this article which seems to work.

<div className="image-container">
  <Image src={path} layout="fill" className="image" />
</div>

SCSS

.image-container {
  width: 100%;

  > div {
    position: unset !important;
  }

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

I wrapped this in a component named <ResponsiveImage />. You can try other rules on the wrapper, such as position: relative.

Inez answered 6/5, 2022 at 21:52 Comment(0)
L
0

You can use these props on the Image tag,

<div className="div-class">
   <Image src={imageLink} layout="fill" objectFit="cover" />
</div>

and wrap the Image tag in a div, just as above. Now you can give width and height to the div with media queries and the image will use that space.

Longshore answered 15/4, 2022 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.