Our classic article on keeping image file sizes small explains why heavy images hurt. This guide shows the modern HTML that lets the browser choose the right image for every screen. It builds on images in HTML.
The problem
A 2400-pixel-wide photo looks sharp on a large retina screen, but a phone in portrait mode only needs a fraction of those pixels. Send everyone the big file and mobile visitors download megabytes they never see. Send everyone the small file and desktop users get a blurry picture.
srcset and sizes
<img src="harbour-800.jpg"
srcset="harbour-480.jpg 480w,
harbour-800.jpg 800w,
harbour-1600.jpg 1600w"
sizes="(max-width: 700px) 100vw, 700px"
width="1600" height="900"
alt="Container ships in the port of Antwerp at sunset">- srcset lists the available files with their real width (
480w= 480 pixels wide). - sizes tells the browser how wide the image will be displayed: the full viewport on small screens, 700 pixels otherwise.
- The browser combines this with the screen’s pixel density and picks the smallest file that still looks sharp.
Modern formats with the picture element
WebP and AVIF compress far better than JPEG and PNG. With <picture> you offer them and keep a fallback for anything that does not understand them:
<picture>
<source type="image/avif" srcset="team.avif">
<source type="image/webp" srcset="team.webp">
<img src="team.jpg" width="1200" height="800" alt="Our team at the office">
</picture>Width, height and layout shift
Always set width and height on images. Modern browsers use them to calculate the aspect ratio and reserve space before the image loads. Without them, text jumps down when images arrive – one of the problems measured by Core Web Vitals as Cumulative Layout Shift. CSS like img { max-width: 100%; height: auto; } keeps the image responsive.
Lazy loading
Add loading="lazy" to images further down the page: the browser only downloads them when the visitor scrolls near. Do not lazy-load the main image at the top of the page, because that delays the most important paint. For that hero image you can even add fetchpriority="high".
Do not forget the alt text
All this technique is useless for blind visitors and search engines if the image has no meaningful description. Read our guide on the alt attribute and SEO. For the full specification, see MDN on responsive images.
Frequently asked questions
Should I convert all my images to WebP or AVIF?
Modern formats are usually much smaller than JPEG at similar quality, and all current browsers support WebP. AVIF compresses even better. Many CMSs and image CDNs convert automatically, so you do not have to keep duplicates by hand.
Why does my page jump while it loads?
Images without width and height attributes take no space until they arrive, so text moves down when they do. Adding the attributes lets the browser reserve the space.