5

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 Answer 1

4

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> 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your help, but I still get the wrong width for the image. For example, if I create a page component that only returns the <img> element, this element is positioned on the left and its width is still respecting the aspect ratio. But if the component returns the <div> + <Image> elements, the image now stretches across the screen.
@Kazuto_Ute Did you set objectFit="contain" as per my example? Here's a sample codesandbox with a working version of my snippet: codesandbox.io/s/epic-margulis-0zkbs.
Yes that is what I mean, the 2nd img element is stretched across the screen. What if I want the img element width to still respect the aspect ratio instead of stretching?
Do you know the aspect ratio in advance? You could add aspectRatio: "<ratio>" to the container style prop if so. Or, alternatively, you'll need to provide an explicit width to the container itself, the image would still maintain its aspect ratio though.
Unfortunately, the image used (hence the aspect ratio) could change from time to time. Ideally I would not like to change the code everytime the design team comes up with a new image. So there is no way to not hard-code the width or the aspect ratio in this case?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.