How to specify image height only and keep aspect ratio in Next.js?

Viewed 3040

I want to specify my image height only and keep the image aspect ratio without hardcoding the width.

In a traditional img element I can do so:

<img src="/logo.png" alt="logo" height={30} />

But if I try using next/image:

<Image src="/logo.png" alt="logo" height={30} />;

I get the following error:

Error: Image with src "/logo.png" must use "width" and "height" properties or "layout='fill'" property.

1 Answers

You can set layout="fill" and objectFit="contain" to your Image so that it maintains its aspect ratio while filling its container. You can then add a wrapper div around the Image component and apply the height to it instead.

<div style={{ position: 'relative', height: '30px' }}>
    <Image
        src="/logo.png"
        layout="fill"
        objectFit="contain"
    />
</div>
Related