简体   繁体   中英

How to position a DIV beneath a fixed DIV with dynamic size

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM