A CSS property that contains the height of the navigation bar

This is a small snippet that I use in my projects to set a CSS property --nav-height with the height of the navigation bar. This is useful when you have a sticky navigation bar that is fixed to the top of the page. You can use this property to offset the page content so that it doesn't overlap with the navigation bar.

const nav = document.querySelector<HTMLElement>(".nav")!;

function setCSSNavHeightProperty(event): void {
console.info("Setting CSS property --nav-height via event type:", event.type);
const box = nav.getBoundingClientRect();
// Set root property of nav height. This is used in offsets. For example @see header.scss.
document.documentElement.style.setProperty(
"--nav-height",
`${box.height}px`
);
}

// Trigger the calculation when the document is loaded
document.addEventListener("DOMContentLoaded", setCSSNavHeightProperty);

// Trigger the calculation on resize.
window.addEventListener("resize", setCSSNavHeightProperty);

I can now use this let's say to offset the .header element.

.header {
/* Also a sensible default; if for some reason js fails. */
margin-block-start: var(--nav-height, 10rem);
}