Search code examples
javascripthtmlcsscss-variables

Get elements heights using JS and pass into CSS variable


I want to get the height of an element and pass it into a css variable. The issue im having is when i try to pass that number into the navHeight variable it ends up returning as undefined.

<script>
    let navHeightTest = document.getElementById("navbar").offsetHeight;
    console.log(navHeightTest); // Returns the nav height as a number
    
    let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest);
    console.log(`Nav Height=${navHeight}`); // Returns undefined 
</script>

CSS

    :root {
        --nav-height: 101px; /* Default Fallback Value */
    }
    .dynamic-margin {
        margin-top: calc(var(--nav-height) + 2.5rem) !important;
    }

Solution

  • Good question - this can get confusing because setProperty returns undefined, not the value you just set.

    Check out the Return value entry in the docs: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty#return_value

    If you observe that the --nav-height variable isn't being updated either it might be because you're missing the units when you call setProperty. Since your default in the CSS is in pixels, and offsetHeight reports the number in pixels, I'm guessing you want pixels. Note the 'px' at the very end of the line.

    let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest + 'px');