DEV Community

Cover image for πŸš€How to Use `next/image` properly in Next.js to Maintain Aspect Ratio
codeek
codeek

Posted on

πŸš€How to Use `next/image` properly in Next.js to Maintain Aspect Ratio

Images are one of the biggest contributors to page load time. Fortunately, Next.js provides the built-in next/image component that automatically optimizes images for better performance while preserving quality.

One of the most common issues developers face is maintaining the correct aspect ratio across different screen sizes without stretching or squashing images.

In this guide, you'll learn the best practices for using the Image component while keeping your images responsive and maintaining their aspect ratio.


Why Use next/image?

Compared to the traditional <img> tag, next/image provides:

  • Automatic image optimization
  • Lazy loading by default
  • Responsive image generation
  • Better Core Web Vitals
  • Reduced layout shifts (CLS)
  • Automatic WebP/AVIF support (when available)

Simply import it:

import Image from "next/image";
Enter fullscreen mode Exit fullscreen mode

1. Using Fixed Width & Height

The simplest approach is specifying both width and height.

import Image from "next/image";

export default function App() {
  return (
    <Image
      src="/images/profile.jpg"
      alt="Profile"
      width={400}
      height={300}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Next.js automatically calculates the aspect ratio from these values and prevents image distortion.


2. Responsive Images Using fill

For responsive layouts, fill is usually the best choice.

First, create a relative parent.

<div className="image-container">
  <Image
    src="/images/banner.jpg"
    alt="Banner"
    fill
    className="image"
  />
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.image-container {
  position: relative;
  width: 100%;
  height: 350px;
}

.image {
  object-fit: cover;
}
Enter fullscreen mode Exit fullscreen mode

fill makes the image fill its parent while object-fit controls how the image scales.


3. Understanding object-fit

The object-fit property determines how your image behaves inside its container.

Cover

<Image
  fill
  src="/images/photo.jpg"
  alt="Photo"
  style={{ objectFit: "cover" }}
/>
Enter fullscreen mode Exit fullscreen mode

βœ… Fills entire container

βœ… Maintains aspect ratio

❌ May crop image

Perfect for:

  • Hero sections
  • Cards
  • Banners

Contain

<Image
  fill
  src="/images/logo.png"
  alt="Logo"
  style={{ objectFit: "contain" }}
/>
Enter fullscreen mode Exit fullscreen mode

βœ… Entire image visible

βœ… Maintains aspect ratio

❌ Empty space may appear

Perfect for:

  • Logos
  • Product images
  • Icons

Fill

<Image
  fill
  src="/images/photo.jpg"
  alt="Photo"
  style={{ objectFit: "fill" }}
/>
Enter fullscreen mode Exit fullscreen mode

⚠️ Stretches the image

⚠️ Does not preserve aspect ratio

Use only when intentional.


4. Using CSS aspect-ratio

Modern browsers support the aspect-ratio property.

<div className="wrapper">
  <Image
    src="/images/mountain.jpg"
    alt="Mountain"
    fill
    className="image"
  />
</div>
Enter fullscreen mode Exit fullscreen mode
.wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 16 / 9;
}

.image {
  object-fit: cover;
}
Enter fullscreen mode Exit fullscreen mode

This is one of the cleanest ways to build responsive image containers.


5. Responsive Width with Automatic Height

You can also make images scale naturally.

<Image
  src="/images/photo.jpg"
  alt="Photo"
  width={1200}
  height={800}
  style={{
    width: "100%",
    height: "auto",
  }}
/>
Enter fullscreen mode Exit fullscreen mode

This keeps the aspect ratio while allowing the image to resize responsively.


6. Using the sizes Prop

When using responsive images, don't forget sizes.

<Image
  fill
  src="/images/banner.jpg"
  alt="Banner"
  sizes="(max-width: 768px) 100vw, 50vw"
  style={{ objectFit: "cover" }}
/>
Enter fullscreen mode Exit fullscreen mode

This helps Next.js generate the most appropriate image size, reducing unnecessary downloads.


7. Local Images

Store images inside the public directory.

public
 └── images
      └── profile.jpg
Enter fullscreen mode Exit fullscreen mode

Use them like this:

<Image
  src="/images/profile.jpg"
  alt="Profile"
  width={500}
  height={500}
/>
Enter fullscreen mode Exit fullscreen mode

8. Importing Images

Instead of using string paths, you can import images directly.

import profile from "@/public/images/profile.jpg";

<Image
  src={profile}
  alt="Profile"
/>
Enter fullscreen mode Exit fullscreen mode

Next.js automatically knows the image dimensions.


9. Remote Images

Configure external domains.

// next.config.js

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.unsplash.com",
      },
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

Now you can safely load remote images.

<Image
  src="https://images.unsplash.com/photo.jpg"
  alt="Unsplash"
  width={800}
  height={600}
/>
Enter fullscreen mode Exit fullscreen mode

Common Mistakes

❌ Setting only width

<Image width={400} />
Enter fullscreen mode Exit fullscreen mode

❌ Stretching images

img {
  width: 100%;
  height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

❌ Forgetting sizes when using fill

<Image fill />
Enter fullscreen mode Exit fullscreen mode

Without sizes, larger images than necessary may be downloaded.


Best Practices

  • βœ… Always provide a meaningful alt attribute.
  • βœ… Prefer fill for responsive layouts.
  • βœ… Use object-fit: cover for banners and cards.
  • βœ… Use object-fit: contain for logos and product images.
  • βœ… Add the sizes prop when using fill.
  • βœ… Store static assets inside the public directory or import them directly.
  • βœ… Avoid stretching images with fixed width and height in CSS.
  • βœ… Use the CSS aspect-ratio property for responsive containers.

Conclusion

The next/image component makes image optimization effortless while helping improve performance, SEO, and Core Web Vitals. By combining fill, object-fit, sizes, and the CSS aspect-ratio property, you can create responsive images that maintain their aspect ratio across every device without distortion.

Following these practices will result in faster-loading pages, better user experiences, and cleaner layouts in your Next.js applications.


πŸŽ₯ Prefer Video Tutorials?

If you'd like to follow along with a practical walkthrough, check out the complete YouTube tutorial:

πŸ“Ί How to use Image properly in Next.js to maintain Aspect Ratio | Next.js Tips

https://www.youtube.com/watch?v=Xi5apyDDeyQ


πŸ›’ Learn to Build a Complete Modern Ecommerce Application

If you're looking to master React by building a production-ready Ecommerce application from scratch, be sure to check out this complete playlist covering authentication, cart, checkout, API integration, routing, state management, deployment, and much more.

πŸš€ Modern Ecommerce Course

https://www.youtube.com/watch?v=SdITjnl-zo8

Happy Coding! πŸš€

Top comments (0)