← Garden

Optimizing images using AVIF

Published
Aug 25, 2023
Updated
Nov 29, 2026
Reading
2 min read
Tags
#html#css#avif#astro

AVIF is an image format based on the AV1 video codec. At the same visual quality, it is usually much smaller than JPEG and noticeably smaller than WebP.

Every major browser supports AVIF, so you can serve it by default and keep JPEG only as a fallback. Jake Archibald’s AVIF has landed has a detailed comparison with other formats.

The trade-off is encoding time: AVIF is slower to encode than JPEG or WebP. That is fine when images are converted once at build time, but it matters when they are resized on the fly.


Serving AVIF

HTML: <picture>

<picture>
<source type="image/avif" srcset="lighthouse.avif" />
<source type="image/webp" srcset="lighthouse.webp" />
<img src="lighthouse.jpg" alt="Lighthouse at dusk" width="1200" height="800" loading="lazy" />
</picture>

The browser picks the first <source> whose type it supports, so put the smallest format first. The <img> is the fallback, and it also carries the alt, the dimensions and loading, which apply whichever source wins.

CSS: image-set()

.hero {
background-image: url("lighthouse.jpg"); /* fallback */
background-image: image-set(
url("lighthouse.avif") type("image/avif"),
url("lighthouse.webp") type("image/webp"),
url("lighthouse.jpg") type("image/jpeg")
);
}

A browser that doesn’t understand image-set() ignores the second declaration and keeps the plain url().

Generating AVIF images

Astro

Astro converts images at build time with its built-in <Picture> component, so no extra packages are needed:

---
import { Picture } from "astro:assets";
import lighthouse from "../assets/lighthouse.jpg";
---
<Picture src={lighthouse} formats={["avif", "webp"]} fallbackFormat="jpg" alt="Lighthouse at dusk" />

This renders the <picture> markup shown above, with the width and height filled in from the source image.

Other Vite projects

The vite-imagetools plugin does the same with an import query:

import lighthouse from "./lighthouse.jpg?format=avif";

Other tools

  • Squoosh: a web app for comparing formats and quality settings side by side.
  • avifenc: the reference command-line encoder from libavif.
  • sharp: a Node library for converting images in your own scripts.