在 pos:relative & 中固定位置 div溢出-y:滚动 [英] Fixed position div inside pos:relative & overflow-y:scroll

查看:37
本文介绍了在 pos:relative & 中固定位置 div溢出-y:滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在带有溢出-y:scroll 的 div 内有一个固定位置的 div,这意味着我希望 div 保持原位,而其余内容正常滚动.我无法弄清楚出了什么问题,有人可以帮忙吗?提前致谢...

.foo {位置:相对;显示:块;宽度:100%;高度:300px;溢出-y:滚动;}.酒吧 {位置:固定;顶部:0;右:0;}

这里是 HTML

<div class="bar"><div><!-- 应该固定的div的结尾--><div class="someOther">...</div><div class="someOther">...</div><div class="someOther">...</div><div class="someOther">...</div></div><!-- 容器结束-->

解决方案

当您将 position:fixed 应用于元素时,您是根据窗口本身而不是其父元素来定位它.您将需要使用 position:absolute 相对于其父级定位子级,只要父级的位置不是 position:static(默认位置).

正如您在示例中所做的那样,将 position:relative 应用于父 .foo,然后将 position:absolute 应用于子级.bar.通常,这将实现将 .bar 对齐到父级顶部的预期结果,但由于父 div 中存在子内容溢出,并且 overflow-y:scroll 滚动所有 子内容,.bar 也必须滚动.请参阅my Fiddle here中的顶部示例.

要解决这个问题,请将您要滚动的内容包装在另一个容器中,并启用 overflow-y:scroll 并删除 上的 overflow-y:scroll.foo 防止 .bar 滚动.

要查看您可以改编的工作示例,请参阅my Fiddle here中的底部示例.

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.

这篇关于在 pos:relative &amp; 中固定位置 div溢出-y:滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆