I wanted this in order to properly set scroll-padding-top for ‘Back to Top’ and other anchor links.
I like setting my primary navigation to Float Right, so when displays get narrower, often the hamburger menu slides down under a wide logo or Site Name, changing the height of the #masthead. This makes setting a static value (e.g. 100px) impractical.
This is done with vanilla JavaScript:
const masthead = document.getElementById('masthead');
const o_root = document.documentElement;
function updateMastheadVar(event) {
if (masthead) o_root.style.setProperty('--masthead-height', masthead.offsetHeight + 'px');
}
document.addEventListener('DOMContentLoaded', updateMastheadVar);
window.addEventListener('resize', updateMastheadVar);Now you can use scroll-padding-top: calc( var(--masthead-height) + 10px ); to give your anchor links the appropriate breathing room.