[英]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,您可以获取<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
更改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.