0
0
NextJSframework~5 mins

Responsive images in NextJS

Choose your learning style9 modes available
Introduction

Responsive images help your website show the right image size for different screen sizes. This makes pages load faster and look good on phones, tablets, and desktops.

When you want your website images to look sharp on all devices.
When you want to save data by loading smaller images on small screens.
When you want to improve your website speed and user experience.
When you want to support different screen resolutions like retina displays.
Syntax
NextJS
import Image from 'next/image'

<Image
  src="/path/to/image.jpg"
  alt="Description of image"
  width={width}
  height={height}
  sizes="(max-width: 600px) 100vw, 50vw"
/>

The Image component from Next.js automatically optimizes images.

The sizes attribute tells the browser how wide the image will be at different screen widths.

Examples
This loads a dog image that is 800x600 pixels. On screens smaller than 600px wide, it uses the full screen width. On bigger screens, it uses half the screen width.
NextJS
import Image from 'next/image'

<Image
  src="/dog.jpg"
  alt="A cute dog"
  width={800}
  height={600}
  sizes="(max-width: 600px) 100vw, 50vw"
/>
This loads a logo image with fixed size and uses priority to load it faster because it is important for the page.
NextJS
import Image from 'next/image'

<Image
  src="/logo.png"
  alt="Company logo"
  width={400}
  height={100}
  priority
/>
This uses the fill prop to make the image fill its parent container and cover it nicely.
NextJS
import Image from 'next/image'

<Image
  src="/landscape.jpg"
  alt="Beautiful landscape"
  fill
  style={{ objectFit: 'cover' }}
/>
Sample Program

This component shows a nature image that changes size depending on the screen width. It uses Next.js Image with sizes to load the best image size. The image has rounded corners for a nice look.

NextJS
import Image from 'next/image'

export default function ResponsiveImageExample() {
  return (
    <main style={{ maxWidth: '800px', margin: 'auto' }}>
      <h1>Responsive Image Example</h1>
      <Image
        src="/nature.jpg"
        alt="Nature scene"
        width={800}
        height={500}
        sizes="(max-width: 600px) 100vw, 50vw"
        style={{ borderRadius: '8px' }}
      />
      <p>This image adjusts size based on your screen width.</p>
    </main>
  )
}
OutputSuccess
Important Notes

Always provide a meaningful alt text for accessibility.

Use the sizes attribute to help browsers pick the right image size.

The Next.js Image component automatically optimizes images for performance.

Summary

Responsive images load the right size for different screens to improve speed and look.

Next.js Image component makes it easy to use responsive images.

Remember to use alt text and sizes for best results.