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 -->
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
To position an element "fixed" relative to the window, you want position:fixed , and can use top: , left: , right: , and bottom: to position as you see fit. This will position yourDiv fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.
A fixed position element is positioned relative to the viewport, or the browser window itself. The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled.
First set position of the parent DIV to relative (specifying the offset, i.e. left , top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want. It's simple and should do the trick well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With