14

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 -->
user2324537
  • 141
  • 1
  • 1
  • 4

2 Answers2

23

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.

Jay Bee Why
  • 558
  • 3
  • 10
5

A fixed elements position is relative to the entire document you are viewing, not whatever the parent element is. If you want that to work, you'd need something like this:

CSS

.foo {
    height : 300px;
    position : relative;
    width : 100%;
}
.bar {
    border-bottom : 1px solid #000;
    height : 50px;
}
.scollable_content {
    height : 250px;
    overflow-y : auto;
}

HTML

<div class="foo">
    <div class="bar"></div>
    <div class="scrollable_content">
        <div class="someOther">...</div>
        <div class="someOther">...</div>
        <div class="someOther">...</div>
        <div class="someOther">...</div>
    </div>
</div>

Here, I created a fiddle for you.

  • thanks for the reply, but the thing is that i need to have '.bar' and scrollable_content at the same level/depth (because of a few z-index manipulations). – user2324537 Apr 26 '13 at 16:40
  • 1
    You'll have to use Javascript to control it, then. Otherwise, you can manipulate your HTML and CSS to do what you need, which is probably easier. – Unexpected Pair of Colons Apr 26 '13 at 17:54