如何将DIV定位在具有动态尺寸的固定DIV下方

时间:2018-06-17 16:37:49

标签: javascript html css

我得到了类似navigation bar的东西,它固定在侧面的顶部。现在我希望它下面有一个content-DIV。问题是,导航栏没有固定的高度。

我怎样才能做到这一点?

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

1 个答案:

答案 0 :(得分:2)

纯Javascript解决方案

使用javascript,您可以获得<div id="nav">的高度和位置,并使用它们来计算<div id="content">的位置:

var navDivElement = document.getElementById("nav");
var contentDivElement = document.getElementById("content");

contentDivElement.style.top = navDivElement.clientHeight + navDivElement.getBoundingClientRect().top + 'px';

Presision

如何获取元素的位置:

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);

来源:https://stackoverflow.com/a/11396681/4032282

如何获取元素的尺寸:

var e = document.getElementById('id')
console.log(e.clientHeight, e.offsetHeight, e.scrollHeight);
  • clientHeight包括高度和垂直填充。
  • offsetHeight包括高度,垂直填充和垂直边框。
  • scrollHeight包含所包含文档的高度(在滚动时大于高度),垂直填充和垂直边框。

来源:https://stackoverflow.com/a/526352/4032282

CSS粘性解决方案

position: fixed;更改导航的position: sticky;并添加top: 0;

这样<div id="content">将被放置在导航栏下,但导航将保持在他的容器顶部。

<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>
相关问题