I am having a problem with high CLS (Content Layout Shift) while using Bootstrap (4.5) grid for two column layout with column order change.
CLS is a Core Web Vital metric. Basically Google sees a problem when webpage's parts are moving when the page is loading. Supposedly this metric is to affect SEO.
On high resolutions my layout consists of two columns. Main content on the right and sidebar on the left. On lower resolutions sidebar content is pushed down below main content. So HTML looks like this:
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 order-lg-2">
</div>
<div class="col-lg-4 order-lg-1">
</div>
</div>
</div>
The problem is that for brief moment while the page renders on desktops, the main content appears on the left side, then milliseconds later it shifts to the right place on the right. With simple pages (with simple DOM or no external resources) the shift is not detectable.
I've prepared an example of such page. (The source code is on github). To measure CLS I am using Lighthouse in Chrome. In my case when I refresh the page I can see columns moving and Lighthouse informs me of CLS value of 0.326. The result might depend on rendering resources so you might get something different. But it seems Google Page Insight gives similar result:
Anyway, is there a way to avoid such shift while the page renders?
To prevent cumulative layout shift from images, always include width and height size attributes on your images and video elements. UA stylesheets from the browser will then add a default aspect ratio based on the element's width and height attributes.
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.
Use col-auto . It will automatically take column size as per content size. It will adjust width as per content in all devices.
It seems the problem is more Chrome related then flexbox or bootstrap. It turned out that the problem is caused by premature renderation. Chrome's parser "yields" (so it triggers rendering):
<script>
tag after reading 50 "tokens" (which I think are basically html tags).The example I provided shows the first case (but actually my real website experiences CLS because the second one). Both of those cases have "bugs" related to them submitted: 1130290 and 1041006.
So the answer to the problem is hoping that the "bugs" will get resolved. In the meantime depending on actual cause you can limit file size or remove <script>
tags.
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