Pure Javascript solution
With javascript, you can get the height and the position of your <div id="nav">
and use them to compute the position of your <div id="content">
:
var navDivElement = document.getElementById("nav");
var contentDivElement = document.getElementById("content");
contentDivElement.style.top = navDivElement.clientHeight + navDivElement.getBoundingClientRect().top + 'px';
Presision
How to get the position of an element:
var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
Source: https://stackoverflow.com/a/11396681/4032282
How to get the dimensions of an element:
var e = document.getElementById('id')
console.log(e.clientHeight, e.offsetHeight, e.scrollHeight);
clientHeight
includes the height and vertical padding.
offsetHeight
includes the height, vertical padding, and vertical borders.
scrollHeight
includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
Source: https://stackoverflow.com/a/526352/4032282
CSS Sticky solution
Change the position: fixed;
of the nav by position: sticky;
and add a top: 0;
.
That way the <div id="content">
will be placed under the nav, but the nav will stay on the top of his container.
<html>
<head>
<style>
#nav {
position: sticky;
top: 0;
}
/* Allow you to play with the browser height to make the vertical scroll appears and use it to see that the nav will stay on top */
#content {
height: 500px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div id="nav">NAV</div>
<div id="content">CONTENT</div>
</body>
</html>