如何使元素相对于其父元素而不是整个屏幕具有固定位置?

Ahm*_*uad 7 css

我遇到这样的情况:当用户向下滚动时,侧边栏的一部分得到固定位置,但是当我抓住位置并将固定的css应用到侧边栏元素时,它会固定到整个屏幕,而不仅仅是父版(这是侧边栏)

我该如何正确设置?

Ahs*_*hid 13

首先了解定位:

固定定位或[位置:固定]

具有固定位置的元素相对于浏览器窗口定位.

相对定位或[位置:相对]

相对定位的元件相对于其正常位置定位.

绝对定位或[位置:绝对]

绝对位置元素相对于具有静态位置的第一父元素定位.

因此,在您的情况下,您的父母div应该拥有,position:relative而您的孩子div应该拥有position:absolute而不是position:fixed

参考链接


ban*_*aka 7

从阅读你的问题我假设你有这样的事情:

 <div class="sidebar">
    <div class="fixed" style="position: fixed;"></div>
 </div>
Run Code Online (Sandbox Code Playgroud)

不幸的是,你可能已经知道,top,left,rightbottom将永远充当相对于在浏览器窗口中positon: fixed的元素.

解决方案是.fixed用另一个div 包装你的div,并在同一个包装器上做你必须做的所有定位而不是.fixeddiv.让我来证明:

HTML:

<div class="sidebar">

    <div class="helper">
        <div class="fixed"></div>
    </div>

 </div>
Run Code Online (Sandbox Code Playgroud)

CSS:

?.sidebar {
    position: relative;
}

.helper {
    position: absolute;
    top: XYZ; left: ZYX; /*where XYZ and ZYX would
                           be the values you were 
                           trying before to give to .fixed*/
}

.fixed {
    position: fixed;
}
Run Code Online (Sandbox Code Playgroud)

在这个小提琴中看到它的实际效果:http://jsfiddle.net/joplomacedo/T2PL5/