使一个DIV在可滚动的DIV中固定

8

有人知道如何在一个可滚动的固定DIV内创建另一个DIV,以便无论我滚动多少,该DIV始终保持在同一位置吗?

非常感谢任何帮助。


您的可滚动 div 是否曾经滚动到屏幕外面? - Jeremy
是的,它就像一个容器,位于屏幕顶部并加载更多信息在其下方。 - William Troup
4个回答

7

试试这个:

<style type="text/css">
    .scrollable {
        width: 200px;
        height: 200px;
        background: #333;
        overflow: scroll;
    }
    .fixed {
        position: absolute;
        top: 180px;
        width: 200px;
        height: 20px;
        background: #fa2;
    }
</style>
<div class="scrollable">
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    <div class="fixed">and I'm fixed</div>
</div>

8
Fredrik的回答不正确,因为.fixed是相对于文档定位的,而不是相对于可滚动的div定位的。在.scrollable中添加position: relative;将解决此问题,但会使.fixed相对于.scrollable内容固定,而不是相对于.scrollable视口固定,我认为这正是您想实现的。 - Zelbus

4

我建议将 div 元素使用绝对定位放置在可滚动的 div 上方。它不会在可滚动的 div 内部,因为它没有必要。


1

我使用了position:sticky解决了这个问题。简单来说,我只是从其他答案中复制了html/css代码。显然,position:sticky在不同的浏览器中支持程度有限。在使用此解决方案之前,请务必进行检查。

<style type="text/css">
    .scrollable {
        width: 200px;
        height: 200px;
        background: #333;
        overflow: scroll;
    }
    .fixed {
        position: sticky;
        top: 80%;
        left: 80%;
        width: 20px;
        height: 20px;
        background: #fa2;
    }
</style>
<div class="scrollable">
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    <div class="fixed">and I'm fixed</div>
</div>

0

在可滚动的 div 中固定 div

#container {
position:absolute;
top:150px;
left:150px;
width:600px;
height:500px;
overflow:hidden;
border:3px dashed #ffff00;
padding:0px;
}

#this_scroll {
position:absolute;
top:0px;
right:0px;
width:99%;
height:99%;
overflow:scroll;
border:2px solid #000;
margin:1px;
background:#B0BDCE;
}

#fix_close {
position:absolute;
top:2px;
right:21px;
width:90px;
height:30px;
overflow:hidden;
border:2px solid #660099;
z-index:10;
background:#8C8C8C;
}


<div id="container">

    <div id="this_scroll">
    <p>some yxyxyx</p><p>some yxyxyx</p>
    </div>

    <div id="fix_close">
        close
    </div>

</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接