Search code examples
htmlcssreactjsimagenext.js

Preserving aspect ratio of image with Next Image component


I'm using Next's Image component to load up a logo. The image is 1843x550 px, but I'm using the width and height properties to size the image for the space it needs to be, which is 83x24 px. Because the aspect ratio I'm using is slightly different, I'm getting the warning:

Image with src "/images/Wordmark_Horizontal.png" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.

The issue is that when I set both width and height to auto with css, my image becomes 128x38 px, larger than I need.

First, why is the image sized to a dimension that I haven't specified? What do I need to do to both preserve the aspect ratio of the image, while also keeping it sized appropriately?

My code:

<Image
    src={'/images/Wordmark_Horizontal.png'}
    width={83}
    height={24}
    alt="logo"
    className="h-auto w-auto"
/>

Solution

  • You can try this using relative positioning for parent container:

    <div style={{ position: "relative", width: "250px", height: "100px" }}>
      <Image src="/mongodb.jpg" alt="logo" layout="fill" objectFit="fill" />
    </div>