簡體   English   中英

如何將DIV放置在具有動態尺寸的固定DIV下

[英]How to position a DIV beneath a fixed DIV with dynamic size

我有固定在側面頂部的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: 在此處輸入鏈接描述

純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';

精確度

如何獲取元素的位置:

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;划分的導航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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM