简体   繁体   English

元素在容器元素内部的固定位置

[英]fixed position of an element inside a container element

I have a parent div in which I want to make the child div stay fixed if the page is scrolled down. 我有一个父div,如果页面向下滚动,我想让子div保持固定。

I've tried to use position:relative; 我尝试使用position:relative; for the parent element and position:fixed; 对于父元素和position:fixed; for the child but it doesn't work because the child div is positioned according to the window object not the parent div. 对于子项,但它不起作用,因为子div是根据窗口对象而不是父div定位的。

Is there any workaround for achieving this with CSS? 是否有解决此问题的方法? If not, some javascript/Jquery tricks to create this ? 如果没有,一些JavaScript / jQuery的技巧来创建这个?

Any hints/suggestions are welcome! 欢迎任何提示/建议!

Thanks! 谢谢!

Use position:relative; 使用position:relative; for the parent and position:absolute; 对于父母和position:absolute; for the child. 为孩子。

For example: 例如:

CSS: CSS:

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 0;
    left: 0;
}

HTML: HTML:

<div class="parent">
    <div class="child">
    </div>
</div>

Jquery.pin might help you here, I guess 我猜Jquery.pin可能会帮助您

It's a JQuery plugin, the feature is to provide a " sticky element to quietly hang around as you scroll down " 这是一个JQuery插件,功能是提供一个“ 粘滞元素,使您在向下滚动时可以安静地徘徊

position:fixed is always relative to the window viewport position:fixed始终相对于窗口视口

You can set the child as position absolute and set its top and left position to fixed values. 您可以将子级设置为绝对位置,并将其顶部和左侧位置设置为固定值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM