固定位置div在pos:relative&溢出-Y:滚动 [英] Fixed position div inside pos:relative & overflow-y:scroll
问题描述
我想在div中使用overflow-y:scroll定位div,这意味着我希望div保持原位,其余内容正常滚动。
我无法弄清楚有什么不对,谁能帮忙?在此先感谢...
.foo {
position:relative;
display:block;
宽度:100%;
height:300px;
overflow-y:scroll;
}
.bar {
position:fixed;
top:0;
right:0;
}
这里是HTML
< div class =foo>
< div class =bar>< div><! - 应该固定的div末尾 - >
< div class =someOther> ...< / div>
< div class =someOther> ...< / div>
< div class =someOther> ...< / div>
< div class =someOther> ...< / div>
< / div><! - 容器结束 - >
固定到一个元素,您将它定位在与窗口本身相关的位置,而不是它的父元素。只要父母的位置不是位置,您就需要使用
,默认位置。 position:absolute
来定位子女相对于其父母的位置:静态
正如你在你的例子中所做的那样,将 position:relative
应用于父节点。 foo
,然后将位置:绝对
应用到子元素 .bar
。通常情况下,这会实现将 .bar
贴到父项顶部的预期结果,但是由于在父div中有子项内容的溢出,并且 overflow-y:scroll
滚动全部子内容 .bar
也必须滚动。请参阅我的小提琴的顶部示例。
解决这个问题,使用 overflow-y:scroll
打开要滚动到另一个容器的内容并移除 overflow-y:scroll
on .foo
以防止 .bar
滚动。
<要查看您可以适应的工作示例,请参阅我的小提琴的底部示例。
I want to have a div with fixed position inside a div with overflow-y:scroll, meaning I want the div to stay in place while the rest of the content scrolls normally. And I can't figure out what is wrong, could anyone help? thanks in advance...
.foo {
position:relative;
display:block;
width:100%;
height:300px;
overflow-y:scroll;
}
.bar {
position:fixed;
top:0;
right:0;
}
And here is the HTML
<div class="foo">
<div class="bar"><div><!-- end of div that should be fixed -->
<div class="someOther">...</div>
<div class="someOther">...</div>
<div class="someOther">...</div>
<div class="someOther">...</div>
</div><!-- end of container -->
When you apply position:fixed
to an element, you are positioning it in relation to the window itself, not its parent element. You'll want to use position:absolute
to position a child in relation to its parent, as long as the parent has a position other than position:static
, the default position.
As you correctly did in your example, apply position:relative
to the parent .foo
and then apply position:absolute
to the child .bar
. Normally, this would achieve the desired result of snapping the .bar
to the top of the parent, but since there is an overflow of child content in the parent div, and overflow-y:scroll
scrolls all the child content, .bar
has to scroll as well. See the top example in my Fiddle here.
To fix that, wrap the content you want to scroll in another container with overflow-y:scroll
on and remove overflow-y:scroll
on .foo
to prevent .bar
from scrolling.
To see the working example that you can adapt, see the bottom example in my Fiddle here.
这篇关于固定位置div在pos:relative&溢出-Y:滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!