I am trying to resolve the avoid large layout shifts in PagespeedInsights
The solution is to set with and height of the below div element.
<div id="HomeNewsEventsWrapper" class="section fixedheight1 introduction table">
@media (min-width:0px) and (max-width:580px) {
#HomeNewsEventsWrapper{
}
}
However, It will also affect the media queries(If the viewport is greater than 580px in real life)
Also, how can I set with and height for every viewport?
I also tries setting height and width to auto but it does not work.
2
Answers
First step Set a fixed height and width for the element in css file , Adjust the height and width for smaller viewports
So it sounds like you have late-loading content which then expands and pushes other content off screen. This is a bad user experience and what CLS is designed to measure. So it’s best to reserve the space needed by that
div
when it’s first create, even if you will only be able to fill it in later. So PSI is basically telling you to set the dimensions of it to do that, and you’ll avoid the CLS.If your
height
should be fixed then just set that using CSS. And you can set differentheight
s in different media queries.If you want the width and height to be a fixed ratio, then you should use the CSS
aspect-ratio
property. See this article, and the MDN docs. This is good in examples where the width is a percentage of the viewport and the height should be based on that, rather than a fixed with.For example, a
1 / 1
aspect ratio means if the width is100px
, then the height will also be set to100px
. A1 / 2
aspect ratio (which can also be written0.5
means if the width is100px
, then the height will be doubled to200px
. As your width changes, the height can automatically be calculated while maintaining this fixed aspect ratio.This is basically what the browser does for you when you provide it with a
width
andheight
as described in this article (that I authored): https://www.smashingmagazine.com/2020/03/setting-height-width-images-important-again/This is also the advice given in the Optimize CLS guide from Google (full disclosure: I maintain this guide now). Search in that article and you will find are several mentions of
aspect-ratio
.