brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the HTML picture element serves other formats and crops per screen

Html
~/tips/tip-html-picture-formats-art-direction

cat ~/tips/tip-html-picture-formats-art-direction.md

Offers the browser alternative image files by format or by media condition, with an img fallback.

One image tag cannot do two jobs: serve a modern format with a fallback, and show a different crop on a phone. The picture element can do both.

<picture>
  <source srcset="photo.avif" type="image/avif">
  <source srcset="photo.webp" type="image/webp">
  <img src="photo.jpg" alt="A harbour at dusk">
</picture>

The browser walks through the source elements in order and uses the first one it can use. The type attribute lets it skip formats it does not support without downloading them. If nothing matches, the img is used.

For art direction, use media instead, so narrow screens get a tighter crop:

<picture>
  <source srcset="wide.jpg" media="(width >= 600px)">
  <img src="narrow.jpg" alt="A harbour at dusk">
</picture>

MDN lists picture as widely available, supported across browsers since March 2016.

The caveat is the img. It is required, since it sets the size and presentation and holds the alt text, so style and describe that element, not the picture. For example, object-fit goes on the img. And if all you want is sharper images on high density screens, MDN recommends srcset on a plain img, which lets browsers pick lower density files in data saving modes.

Further reading: MDN: picture

More Html tips import { format } from "dates"; width="640" height="360" poster="demo.jpg"> The HTML optgroup element puts headings inside a long dropdown srclang="en" label="English" default> An HTML noindex meta tag keeps one page out of search results All Html tips (14) All topics

Link