Dynamic height for an image using Tailwind and Next.js

Viewed 36

I'm using Tailwind with Next.js, and I'm trying to figure out how to dynamically set the height for the "figure" element. Here's how I have it setup:

<figure className={format === "wide" ? wideImageClass : narrowImageClass}>
   <Image
     src={url}
     alt={alt}
     width={width}
     height={height}
     layout="fill"
     objectFit="contain"
   />
   <figcaption className="font-display text-sm text-gray-700">
     {caption}
   </figcaption>
 </figure>;
                 

Here's what narrowImageClass would be. It's essentially computing the height of the image container.

  const narrowImageClass = `relative my-6 h-[${Math.round(
              (articleWidth * height) / width
            )}px]`;

When this renders into HTML the classes look correct, but the height of figure ends up being set to 0 and so nothing renders on my screen. Any idea why this might be happening and how to fix it?

Thanks!

1 Answers
Related