0

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

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! i just tried figuring it out with chatGPT and it gave the same thing essentially - i was missing the "px". I did not know that setProperty returns undefined though, that is super helpful knowledge. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.