Viewport Height Calculation Fix CSS Variable, vh fix

Maybe you discovered there is a problem with almost all browsers 🙂

Viewport height vh unit doesnt work properly. Why ? Well because we usualy need Visible Viewport Height but what we get is current window viewport height. But ofcourse in most cases this is not exacly what we need. When we have some sticky header or moving header footer or gsap site this becomes a headache.

This js fixes that. it adds –vh css variable for calculated 1% of the vh and then we can use this whereever we want.

Load this script on all of your page.

<script>
function setViewportHeight() {
var vh = window.innerHeight * 0.01; 
document.documentElement.style.setProperty('--vh', `${vh}px`);
}
setViewportHeight();
window.addEventListener('resize', setViewportHeight);
</script>

This will add calculated real visible viewport height vh on your page;

Now you can use this easily everywhere with css because it is just a simple css variable.

For example if you need 100% vh visible vh for a section or container you can use this;

calc(var(--vh, 1vh) * 100)

or lets say you want to make 100% vh but 20px less this works nice when you want some border arounds padding ..etc

calc(var(--vh, 1vh) * 100 - 20px)