Sep 25, 2022
White Arrow icon
Back to all Elements

Dynamic Height

A (custom code) solution that combines CSS variables and Vanilla JavaScript for the shrinking / growing of browser top & bottom bars.

Dynamic height property

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>

Copy

What is this sorcery??

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!


What are the use cases?

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);
}

Copy

Preview:

Share:

Try avoiding using "Transition: All". It is heavy on the browser's engine.

Might also interest you:

3d Video Slider (swiper.js)

Cloneable
CMS
JavaScript

A 3d slider with video items, plays and pauses on click & slide change.

Read more
White Arrow icon

Webflow Dashboard Workspaces Hack

Webflow UI Hack
Code
CSS

Convert the Workspaces dropdown to an open sidebar with custom order.

Read more
White Arrow icon

Glossary

Cloneable
JavaScript
CMS

A clonable for creating an Alphabetical glossary

Read more
White Arrow icon