Top and bottom bars of mobile browsers shrink / grow according to scrolling.
In iOS for example, when we scroll down, the bottom bar completely disappears, and the top bar shrinks, but when we scroll up, the bottom bar "comes back" and the top bar grows.
This creates a situation which 100vh element will wither be too big, or too small... meh..
Here is a (custom code) solution that combines CSS variables and Vanilla JavaScript.
On a mobile device, try scrolling down to the end of the image section, and then scrolling back up. Notice the size of the DIV on the right.
<script>
const root = document.querySelector(':root');
window.addEventListener('load', getInnerHeight);
window.addEventListener('scroll', getInnerHeight);
window.addEventListener('resize', getInnerHeight);
function getInnerHeight() {
root.style.setProperty('--full', window.innerHeight + 'px');
}
</script>
So, first we use some JS to establish our :root element as a constant.
Then we add 3 event listeners - load, scroll, resize. Every time one of these will happen, our function will run.
Now for the fun stuff:
The getInnerHeight function sets the property '--full' (which is a variable) of the :root element to be the exact size of the windows inner height (in px).
Now whenever we use this variable in our CSS, it will always be updated to the actual innerHeight!
For starters, like in the first example - a full page element that keeps all content visible at all times. Especially if position:sticky is also at play.
Another use case would be a fixed div at the bottom of the screen. Could be a banner or a marquee. Here we can use the CSS calc() function with our var() inside like so:
.bottom-banner {
top: calc(var(--full) - 60px);
}
Destin's Youtube channel Smarter Every Day is one of my favourite places on the web.