๐ผ๏ธ 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) | Slowest | Ultra-optimize, bandwidth sensitive |
WebP | ๐ฅ Better than JPEG/PNG | Very good | โ Almost all modern browsers | Fast | General web use |
JPEG | ๐ฅ OK | Good | โ Universal | Fastest | Legacy support, photos |
PNG | โ Big files | Perfect (lossless) | โ Universal | OK | Graphics, transparency |
GIF | ๐ด Outdated | Low (8-bit only) | โ Universal | Slow | Animations 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>