Skip to main content

๐Ÿ–ผ๏ธ Image

How to optimize images for the web.

Formatsโ€‹

Format๐Ÿ”ฅ Compression๐Ÿ–ผ๏ธ Quality๐Ÿง  Browser Supportโฑ๏ธ Decode Speed๐Ÿงช Best For
AVIF๐Ÿฅ‡ Best (tiny size)Great (supports HDR)~95% (no Safari <16)SlowestUltra-optimize, bandwidth sensitive
WebP๐Ÿฅˆ Better than JPEG/PNGVery goodโœ… Almost all modern browsersFastGeneral web use
JPEG๐Ÿฅ‰ OKGoodโœ… UniversalFastestLegacy support, photos
PNGโŒ Big filesPerfect (lossless)โœ… UniversalOKGraphics, transparency
GIF๐Ÿ‘ด OutdatedLow (8-bit only)โœ… UniversalSlowAnimations only (consider APNG/WebP instead)

Aspect Ratioโ€‹

Prefer aspect-ratio + object-fit: cover to maintain the aspect ratio of images.

.image-wrapper {
aspect-ratio: 16 / 9;
width: 100%;
}

.image-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
}

For plain HTML, just lock the width and height on <img>.

Templatesโ€‹

Just One Plain Imageโ€‹

<img src="image.jpg" alt="Always include alt text" />

Lazy Loadingโ€‹

Use loading="lazy" to lazy load images.

<img src="image.jpg" alt="Always include alt text" loading="lazy" />
warning

Don't use loading="lazy" on images that are above the fold or critical to the page.

Multiple Formatsโ€‹

Use <source> inside <picture> to load different formats based on browser support.

<picture>
<source srcset="image.webp" type="image/webp" />
<source srcset="image.jpg" type="image/jpeg" />
<img src="image.jpg" alt="Always include alt text" />
</picture>

Multiple Resolutionsโ€‹

Use srcset to load iamges with different resolutions based on the viewport size.

<img
srcset="image-small.jpg 400w, image-medium.jpg 800w"
src="image.jpg"
alt="Always include alt text"
/>

Multiple Display Sizes (Responsive)โ€‹

Use srcset + sizes to load images with different display sizes based on the viewport size.

<img
srcset="image-small.jpg 400w, image-medium.jpg 800w"
sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px"
src="image.jpg"
alt="Always include alt text"
/>

Captionโ€‹

Use <figure> and <figcaption> to add a caption to the image.

<figure>
<img src="image.jpg" alt="Always include alt text" />
<figcaption>Some description</figcaption>
</figure>

All Togetherโ€‹

<figure>
<picture>
<source
srcset="image-small.webp 400w, image-large.webp 800w"
type="image/webp"
sizes="(max-width: 600px) 100vw, 50vw"
/>
<source
srcset="image-small.jpg 400w, image-large.jpg 800w"
type="image/jpeg"
sizes="(max-width: 600px) 100vw, 50vw"
/>
<img src="image-large.jpg" alt="Always include alt text" />
</picture>
<figcaption>Some description</figcaption>
</figure>