JavaScript - Auto adjust top nav bar height using CSS and JavaScript

by
Jeremy Canfield |
Updated: April 09 2023
| JavaScript articles
Let's say you have the following HTML.
<!DOCTYPE html>
<html>
<head>
<style>
.fixed {
position: fixed;
background-color: tan;
width: 100vw;
}
</style>
</head>
<body>
<div class="fixed">Fixed<br />Div</div>
<img src="/images/jeremy.jpg">
</body>
</html>
This creates an issue where the fixed div covers the other HTML.
CSS and JavaScript can be used to solve this issue. Here is the HTML and CSS and JavaScript. The important markup here is :root { --navHeight: 40px; } and padding-top: var(--navHeight). It doesn't matter that navHeight is set to 40px in this example as the JavaScript will auto-adjust the navHeight on page load and page resize.
Of course, you'll probably place the CSS in it's own file (e.g. custom.css) and the JavaScript in it's own file (e.g. navHeight.js) and then reference the CSS and JavaScript files in your base.html file.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--navHeight: 40px;
}
html, body {
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 100;
height: 100%;
width: 100%;
padding-top: var(--navHeight);
}
.fixed {
position: fixed;
background-color: tan;
width: 100vw;
}
</style>
<script>
function setNavHeight() {
const nav = document.querySelector('nav');
const root = document.querySelector(':root');
root.style.setProperty('--navHeight', `${nav.clientHeight * 1.0}px`)
}
window.addEventListener('resize', setNavHeight);
window.addEventListener('DOMContentLoaded', setNavHeight);
</script>
</head>
<body>
<div class="fixed">Fixed<br />Div</div>
<img src="/images/jeremy.jpg">
</body>
</html>
Did you find this article helpful?
If so, consider buying me a coffee over at