DIV与位置:绝对动态扩展到视口底部?

问题描述 投票:0回答:1

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

这就是我的意思: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;
}
<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 class="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>	
</body>
html css position height absolute
1个回答
0
投票

特曼尼在评论中说道。使用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>
© www.soinside.com 2019 - 2024. All rights reserved.