If you have a <picture>
element with image sources at different aspect ratios at different breakpoints, what is the best way to minimize CLS by using aspect-ratio and media queries in CSS?

- 2,798
- 1
- 14
- 21
2 Answers
For <picture>
, you should be fine as long as each <source>
image has the same aspect-ratio in your responsive image snippet:
<img width="1000" height="1000"
src="puppy-1000.jpg"
srcset="puppy-1000.jpg 1000w,
puppy-2000.jpg 2000w,
puppy-3000.jpg 3000w"
alt="Puppy with balloons"/>
For <picture>
where each <source>
has a different aspect-ratio, browsers are awaiting standardization of width/height being recommended for each <source>
for the art-direction use-case:
<picture>
<source srcset="https://via.placeholder.com/600x279" media="(max-width: 599px)" width="600" height="279">
<source srcset="https://via.placeholder.com/1500x300" media="(max-width: 991px)" width="1500" height="300">
<img src="https://via.placeholder.com/1500x300" width="1500" height="300">
</picture>
In the meantime, you can provide height
through padding-top CSS hacks, with different media-queries per <picture>
breakpoint.

- 2,798
- 1
- 14
- 21
-
width/height in
is working now in Chrome 90 (the linked github issue was closed) – Zanon Apr 17 '21 at 18:20
The source element supporting dimension attributes is now part of the HTML standard — https://html.spec.whatwg.org/multipage/embedded-content.html#the-source-element
The standardisation matches the example implementation @addyo already provided.
For the art-direction use-case of a <picture>
, where each <source>
has a different aspect-ratio, each <source>
can provide its own width
and height
value.
<picture>
<source srcset="https://via.placeholder.com/600x279" media="(max-width: 599px)" width="600" height="279">
<source srcset="https://via.placeholder.com/1500x300" media="(max-width: 991px)" width="1500" height="300">
<img src="https://via.placeholder.com/1500x300" width="1500" height="300">
</picture>
Implementation for browser support is underway and should be trackable in caniuse soon.

- 186
- 1
- 5