简体   繁体   English

如何将DIV放置在具有动态尺寸的固定DIV下

[英]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. 我有固定在侧面顶部的navigation bar类的东西。 Now I want to have a content-DIV which is beneath it. 现在,我想在其下面放一个content-DIV The problem is, that the navigation bar has no fixed height. 问题是导航栏没有固定的高度。

How can I achieve this? 我该如何实现?

HTML: HTML:

<div id="nav">
this is my navigation bar
</div>
<div id="content">
HERE <br>
IS <br>
MUCH <br>
CONTENT
</div>

CSS: CSS:

#nav {
  position: fixed;
  background: lightblue;
}

JSFIDDLE: enter link description here JSFIDDLE: 在此处输入链接描述

Pure Javascript solution 纯Javascript解决方案

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"> : 使用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 精确度

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 资料来源: 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. clientHeight包括高度和垂直填充。
  • offsetHeight includes the height, vertical padding, and vertical borders. offsetHeight包括高度,垂直填充和垂直边框。
  • scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders. scrollHeight包括所包含文档的高度(在滚动的情况下将大于高度),垂直填充和垂直边框。

Source: https://stackoverflow.com/a/526352/4032282 资料来源: https : //stackoverflow.com/a/526352/4032282

CSS Sticky solution CSS置顶解决方案

Change the position: fixed; 更改position: fixed; of the nav by position: sticky; position: sticky;划分的导航position: sticky; and add a top: 0; 并添加一个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. 这样, <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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