htmlcssweb-performancecumulative-layout-shift

Cumulative Layout Shift problem - how to fix an element from horizontally shifting?


I have a basic header that has a max-width and margin applied (standard stuff) in order to position it horizontally in the middle of the page.

However, when I run a lighthouse report, it shows a horizontal shift.

Below is my HTML, CSS and the screenshot of the shift.

I would appreciate it if anyone else experienced this problem before and know how to combat this horizontal shifting. Thanks.

Screenshot: CLS horizontal shifting

HTML:

<header class="header" role="banner" itemscope="" itemtype="http://schema.org/WPHeader">
    <div class="header__container"> 
        <div class="header__search">
            <form class="header-search">
                <input type="text" placeholder="" class="header-search__input" >
                <button type="submit" class="header-search__button" name="Search" aria-label="Search">
                    <i class="fa fas--search"></i>
                </button>
            </form>
        </div>
    </div>
</header>

CSS:

.header {
  width: 100%;
  background: #321428;
}

.header__container {
  padding: 10px;
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: auto 1fr;
  grid-template-columns: auto 1fr;
  -ms-grid-rows: auto;
  grid-template-rows: auto;
  grid-gap: 10px;
  width: 100%;
  max-width: 1500px;
  margin: 0 auto;
}
@media (min-width: 768px) {
  .header__container {
    -ms-grid-columns: auto 1fr auto;
    grid-template-columns: auto 1fr auto;
    -ms-grid-rows: auto 40px;
    grid-template-rows: auto 40px;
    grid-gap: 20px;
  }
}
@media (min-width: 960px) {
  .header__container {
    -ms-grid-columns: 21.6% 1fr 25.7%;
    grid-template-columns: 21.6% 1fr 25.7%;
    padding: 10px 20px 15px;
    height: 115px;
  }
}

Solution

  • I found the answer to my own question.

    The horizontal shift happens because the page is still rendering the remaining parts of the page which is below the fold, causing the scroll bar to appear later on.

    To combat this situation, I simply added html { overflow-y: scroll; } to enforce the scrollbar at first paint. Since then, my lighthouse report came back with no major CLS issues.