Content Shifting, also known as Content Jumping, happens when elements of a web page change height while a page is loading. This can be disorientating to users, and in extreme cases can cause problems if a user clicks on an element as it moves, causing undesired input. It’s also expected in 2021 that search engines will begin penalising content that exhibits content shifting.
To avoid content shifting, the element’s height would be set regardless of the dynamic content it contains.
When using Vue or React JavaScript frameworks, I’ve found that CSS parameters are useful. In my example, a Vue app loads dynamic content and displays it. Unfortunately this causes content shifting.
To avoid this, I pass the number of rows in the HTML/view:
1
| <div class="container" style="--preload-row-count: {{ $count }};">...</div> |
In my CSS/SASS stylesheet, I then use this parameter in a calculation. There are two columns, so the number of rows is divided by 2. It is then multiplied by the height of a single row, and a minimum height is set for the container so that it will not shift:
1 2 3 4
| .container{
--calculated-board-rows: calc( var(--preload-row-count) / 2);
min-height: calc( var(--calculated-board-rows) * 50px );
} |
This fairly simple method is an effective way to stop content shifting using CSS parameters and calculations.