skip to Main Content

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


  1. First step Set a fixed height and width for the element in css file , Adjust the height and width for smaller viewports

    #HomeNewsEventsWrapper{
      height: 200px;
      width: 100%;
      background:red;
    }
    @media (max-width: 580px) {
      #HomeNewsEventsWrapper {
        height: 150px; 
        width: 100%; 
      }
    }
    <div id="HomeNewsEventsWrapper" class="section fixedheight1 introduction table">
    Login or Signup to reply.
  2. 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 different heights 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 is 100px, then the height will also be set to 100px. A 1 / 2 aspect ratio (which can also be written 0.5 means if the width is 100px, then the height will be doubled to 200px. 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 and height 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search