Responsive images adapt to different screen sizes.
HTML approach:
1<picture>2 <source media="(min-width: 1024px)" srcSet="large.webp" type="image/webp" />3 <source media="(min-width: 768px)" srcSet="medium.webp" type="image/webp" />4 <img5 src="small.jpg"6 alt="Description"7 loading="lazy"8 decoding="async"9 />10</picture>
React component:
1function ResponsiveImage({ src, alt, sizes }) {2 return (3 <img4 src={src}5 alt={alt}6 srcSet={`${src}?w=400 400w, ${src}?w=800 800w, ${src}?w=1200 1200w`}7 sizes={sizes || "(max-width: 768px) 100vw, 50vw"}8 loading="lazy"9 className="responsive-img"10 />11 );12}1314// Usage15<ResponsiveImage16 src="/photo.jpg"17 alt="Mountain landscape"18 sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw"19/>
With Next.js Image:
1import Image from "next/image";23<Image4 src="/photo.jpg"5 alt="Description"6 width={800}7 height={600}8 sizes="(max-width: 768px) 100vw, 50vw"9 priority={true} // for above-the-fold10/>
Best practices: