Reputation: 4812
I got something like a navigation bar
which is fixed on the top of the side. Now I want to have a content-DIV
which is beneath it. The problem is, that the navigation bar has no fixed height.
How can I achieve this?
HTML:
<div id="nav">
this is my navigation bar
</div>
<div id="content">
HERE <br>
IS <br>
MUCH <br>
CONTENT
</div>
CSS:
#nav {
position: fixed;
background: lightblue;
}
JSFIDDLE: enter link description here
Upvotes: 0
Views: 2116
Reputation: 888
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';
var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
Source: https://stackoverflow.com/a/11396681/4032282
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
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>
Upvotes: 2