4

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.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Kazuto_Ute
  • 679
  • 6
  • 20

1 Answers1

3

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>
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    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 element, this element is positioned on the left and its width is still respecting the aspect ratio. But if the component returns the
    + elements, the image now stretches across the screen.
    – Kazuto_Ute Sep 20 '21 at 23:31
  • @Kazuto_Ute Did you set `objectFit="contain"` as per my example? Here's a sample codesandbox with a working version of my snippet: https://codesandbox.io/s/epic-margulis-0zkbs. – juliomalves Sep 21 '21 at 11:17
  • 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? – Kazuto_Ute Sep 21 '21 at 11:21
  • Do you know the aspect ratio in advance? You could add `aspectRatio: ""` 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. – juliomalves Sep 21 '21 at 12:35
  • 1
    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? – Kazuto_Ute Sep 22 '21 at 01:11
  • I guess we'll never know... – Denny Nov 13 '22 at 00:58