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?
To reduce layout shifts caused by ads, embeds, and iframes, do things like: Reserve ad slot size (preferably the largest) before loading the ad library. Move ads to the bottom or out of the viewport. Use placeholders when there is no ad available to show.
A good cumulative layout score is anything less than 0.1.
Avoid placing ads near the top of the viewport # Ads near the top of the viewport may cause a greater layout shift than those at the middle. This is because ads at the top generally have more content lower down, meaning more elements move when the ad causes a shift.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With