带position:的DIV可以动态扩展到视口的底部吗?

时间:2019-02-24 22:18:05

标签: html css position height absolute

是否可以使用position:absolute指定DIV的最大高度,以便如果它向下向下超过视口,则会出现滚动条? 即,向用户“ overflow-y:滚动;”无需静态指定高度? (即使您调整窗口大小,它也可以正常工作。)

我的意思是:https://jsfiddle.net/x5efqtv2/2/ (另请参见下文)

P.S .:我可以用JavaScript解决,如果有的话,我对纯CSS解决方案很感兴趣。

谢谢!

"
div {
    border: 1px solid red; 	/* just to see where the DIVs exactly are */
    margin: 5px; 			/* ditto */
}
.float-over-content {
    position: absolute; 
    max-height: 100px;  
    overflow-y: scroll; /* works with static max-height only? */
    z-index: 10;
    background-color: white;
}

1 个答案:

答案 0 :(得分:0)

Temani在评论中说了什么。使用calc函数和视口的视图高度(vh)。查看下面的代码段。我添加了一个按钮,该按钮将向元素添加更多行文本,您可以看到它扩展到适合视口的位置,并且溢出成为滚动内容。

document.getElementById("add-a-line").addEventListener("click", function(){
  document.getElementById("float-over-content").insertAdjacentHTML('afterbegin','Make this reach exactly to the bottom<br/>' );
});
div {
    border: 1px solid red; 	/* just to see where the DIVs exactly are */
    margin: 5px; 			/* ditto */
}
#float-over-content {
    position: absolute; 
    max-height: calc(100vh - 47.4px);  
    overflow-y: scroll; /* works with static max-height only? */
    z-index: 10;
    background-color: white;
}

#add-a-line{
  position:fixed;
  right: 0;
  width: 200px;
  height: 20px;
  
  background-color: #0f0;
}
<body>    
  <div id="upper">This one is above the position:absolute one</div>
  <div style="position: relative">
    <!-- this is needed for position:absolute below to put the div under "upper" -- or so I think -->
    <div id="float-over-content">
    <!-- I WANT TO DEFINE THE MAX-HEIGHT OF THIS DIV SUCH THAT IF IT REACHES THE BOTTOM OF THE VIEWPORT, A SCROLL BAR SHOULD APPEAR: (AS OPPOSED TO NOW, WHEN ITS HEIGHT REACHES 100px) -->
    Make this reach exactly to the bottom<br/>
    <!-- X times... -->
    Make this reach exactly to the bottom<br/>
    </div>
  </div>
  <div id="lower">
    This one is "behind" the position:absolute one (it partially covers this one)
  </div>
  
  <div id="add-a-line">
    Click to add a line
  </div>
</body>