将DIV固定在可滚动的DIV中

Make DIV fixed inside a scrollable DIV

本文关键字:DIV 滚动      更新时间:2023-09-26

现在有人知道如何在另一个可滚动的div中创建一个div吗?这样,无论我滚动多少,div都会保持在同一个位置?

如有任何帮助,我们将不胜感激。

试试这个:

<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>

我建议将div绝对定位在可滚动div上。它不会是可滚动div中的,因为它不需要。

可滚动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>

我使用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>