#Keep Original Image Ratio

3 messages · Page 1 of 1 (latest)

sterile estuary
#

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>
sour waspBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

wild cargo
#

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
/>