Next.js Discord

Discord Forum

Keep Original Image Ratio

Unanswered
Devon Rex posted this in #help-forum
Open in Discord
Devon RexOP
Hello,

I work on a website where we have a mobile view on the desktop, therefore I want my images to span across the entire width of their container, and use the original height of the image.

When using the Image component, we have to either specify the width/height of the image OR use the fill property. Therefore, and since I want the width to be dynamic and use all the available width, I have to use the fill property. However, to achieve the desired result, I then have to wrap the image in a div container and reset its position. While this method works, it is a bit hacky.

Is there a better Next.js approach to do that?

const BrandImageWrapper = emotionStyled.div`
  position: relative; // While this position does not do anything, it removes the console warning saying that the parent should either have position fixed, sticky or relative
  
  img {
      position: relative !important;
      object-fit: cover;
  }
`;

<BrandImageWrapper>
  <Image
    fill
    src={media.src}
    alt={media.alt}
    priority
    sizes={`(max-width: ${theme.breakpoints.values.sm}px) 90vw, 100vw`}
  />
</BrandImageWrapper>

2 Replies

Holland Lop
You can use width and height 0 like below:
<Image
src="your-image.jpg"
width={0}
height={0}
sizes="100vw" // Ensures full viewport width
style={{ width: '100%', height: 'auto' }} // Maintains aspect ratio
/>
Devon RexOP
@Holland Lop Thanks, I was hoping for a less hacky solution 😁