Based on the AV1 video codec, AVIF usually provides the best quality and perforance for images. AVIF is relatively new but offers significant compression gains over other image formats like JPEG and WebP.
Image format | Size |
---|---|
AVIF | 51.8 KB |
WebP | 153 KB |
JPEG | 493 KB |
This is based on the image used for the home page.
AVIF is supported by all modern browsers. See here for a detailed comparison between image types.
Usage
Using CSS background-image property:
.image {
background-image: url("images/awesome.jpg"); /* fallback */
background-image: image-set(
url("images/awesome.avif") type("image/avif"),
url("images/awesome.webp") type("image/webp"),
url("images/awesome.jpg") type("image/jpeg")
);
}
Using the <picture>
element:
<picture>
<source type="image/avif" srcset="cow.avif" />
<source type="image/webp" srcset="cow.webp" />
<!-- fallback -->
<img src="cow.jpg" srcset="cow.png" alt="Cow" />
</picture>
The browser will use the first format supported. Place formats with better compression on top.
Browsers not supporting <picture>
or image-set()
CSS function will ignore them and fallback to the supported.
Generating AVIF Images
NPM Package
Using vite-imagetools
npm package:
$ yarn add --dev vite-imagetools
<script>
import image from 'images/cat.jpg?format=avif';
</script>
<img src={image} alt="cat" />
Above code is in Svelte but this can be used on any project using Vite.
Other Tools
Squoosh is a web app to compare image compression with various formats.