2 years ago

#72265

test-img

Tyler Morales

How to style a Next Image tag inside a figure tag

I am trying to optimize my website with Next's native Image tag. However, I am struggling to set variable heights on the images. Since the images can have different height, i'm not sure how that works with Next Image.

The problem

How to set variable heights on each image coming in from an API?

Initial Approach

Without using Next/Image, I am able to achieve the result of a a grid like structure with jagged image heights.

<figure key={index} className="break-inside-avoid-column">
  <img src={img.url} alt={img.altText} />
  <figcaption>
    {img.altText}
  </figcaption>
</figure>

This is what displays in the browser and the effect I am trying to convert to with Next image:

enter image description here

New Approach

After swapping out the old img tag to Image, this is what I have come up with. Everything works, but the variable heights of each image are all set to the same height. My goal is to have the heights of image be variable, only the widths should be the same.

<figure
  key={index}
  className="block mb-10 text-center break-inside-avoid-column">
  <Image
    layout="responsive"
    width="100%"
    height="100%"
    className="object-cover rounded-xl"
    src={img.url}
    alt={img.altText}
  />
  <figcaption className="z-10 mt-4 text-sm italic text-gray-600">
    {img.altText}
  </figcaption>
</figure>

Here is the result of using the Image tag in the browser:

enter image description here

javascript

css

reactjs

next.js

nextjs-image

0 Answers

Your Answer

Accepted video resources