With the new Web Vitals incoming I have a problem with my sticky navigations/menus. In fact most pages will have :-(
The problem is that I use an approach like bootstrap affix to make the menu sticky when it would leave the viewport. But every time the menu leaves the viewport (and enters it as well) and the position is set from relative/static/absolute
to fixed
it increases CLS (Cumulative Layout Shift). I realize that changing the position to fixed
will result in a layout shift because the element is removed from the layer and all following elements will be shifted to the top.
BUT: That's why I came up with some solutions and the best I think is that I use a wrapper with a specific height around the menu. So when the position of the menu changes to fixed the wrapper still exists and does not change in position or height, which means that no following elements has to shift. But the CLS is still counting up. And I do not know what to do to make my menus sticky without affecting the CLS which is important. Btw I cannot use position: sticky because there is not enough browser support. Because if my researches are correct position: sticky
works without negatively affecting the CLS, my solution does not although the user **does not see any difference at all **....
Here comes some pseudo code to be more visual:
...
<body>
<h1>
Headline
</h1>
<p>
Here is some elements an stuff
</p>
<div class="menu-wrapper">
<div class="menu">
<ul>...........</ul>
</div>
</div>
<p>
More elements and stuff. Nothing shifting because the wrapper always has the same height.
</p>
...
</body>
...
.menu-wrapper {
height: 60px;
width: 100%;
}
.menu {
height: 60px;
width: 100%;
position: static;
}
.menu.affix {
position: fixed;
top: 0;
}
Any ideas? Thank you very much!