如何将div固定到位置,其他元素直接在此div下开始

时间:2020-06-08 12:31:01

标签: html css

我有一个div,其位置固定在页面顶部。这是唯一固定的。

如何在此固定div下直接(精确地)开始其余内容。我不知道固定div(文本内容与图像混合在一起)的高度。

目前,我通过插入<p>$nbsp;</p>标签将内容大致定位在其下方,但这并不是一个很好的解决方案。

2 个答案:

答案 0 :(得分:1)

由于您不知道固定元素的高度,因此建议您使用javascript获取高度,然后将其下的元素的边距顶部设置为与固定元素相同的高度。

HTML

<body onload="onPageLoad()">
   <div id="fixed"></div>

   <div id="under-fixed">
       This is below the fixed element
   </div>
</body>

CSS

#fixed {
  position: fixed;
  top: 0;
}

JavaScript

 function onPageLoad() { 

    //Get the height of the fixed element
    height = document.getElementById('fixed').offsetHeight;

    //Set the margintop of the element under the fixed one to the height of the
    //fixed one
    document.getElementById("under-fixed").style.marginTop = height+"px";
 }

编辑:

如果您不想使用javascript进行操作,则可以将固定元素放在一个位置:粘性;

然后,您必须确保粘滞元素是身体的直接子元素(或直接延伸到页面底部的容器的直接子元素)。然后,该位置粘滞元素将停留在页面顶部,而粘滞元素下面的内容将停留在页面下方(直到您滚动课程)。

CSS

.sticky-element {
   position: sticky;
   top: 0;
   z-index: 999;
}

答案 1 :(得分:0)

您可以使用绝对位置-

<div class="fixed-div">I  am a fixed div </div>
...
...
...
Rest of your elements...

将类应用为-

.fixed-div {
  position: absolute;
  top: 0;
  left: 0;
}
相关问题