【发布时间】:2019-02-25 08:04:27
【问题描述】:
是否可以使用 position:absolute 指定 DIV 的最大高度,这样如果它向下越过视口,就会出现滚动条? 即,对用户“溢出-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;
}
<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>
【问题讨论】:
-
如果你知道上部元素的高度,你可以做 max-height:calc(100vh - h);其中 h 是已知高度
-
嗨@TemaniAfif,不幸的是我不知道上部元素的高度。 (而在现实生活中,它甚至不仅仅是一个 DIV,而是上面更多的内容。)通过 JS 获取它是唯一的选择吗?
-
其实,我没有看到任何纯 CSS 解决方案,但请继续等待,可能有人会带来一些魔法;)
标签: html css position height absolute