Fixed position div inside pos:relative & overflow-y:scroll

css, html, web

Solution

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.

Problem

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

Original source