I run into situation that when user scroll down, a part of the sidebar gets fixed position, however when I catch the position and apply fixed css to the sidebar element, it gets fixed to whole screen, not just the parent (which is sidebar)
how do I setup this correctly?
First Understand Positioning:
Fixed Positioning OR [ position:fixed ]
An element with fixed position is positioned relative to the browser window.
Relative Positioning OR [ position:relative ]
A relative positioned element is positioned relative to its normal position.
Absolute Positioning OR [ position:absolute ]
An absolute position element is positioned relative to the first parent element that has a position other than static.
So in your case your parent div
should have position:relative
and your child div
should have position:absolute
instead of position:fixed
Reference Link
From reading your question I assume you have something like this:
<div class="sidebar">
<div class="fixed" style="position: fixed;"></div>
</div>
Unfortunately as you probably know by now, top
, left
, right
or bottom
will always act relative to the browser window on positon: fixed
elements.
The solution is wrapping your .fixed
div with another div, and do all the positioning you have to do on that same wrapper and not on the .fixed
div. Let me demonstrate:
The HTML:
<div class="sidebar">
<div class="helper">
<div class="fixed"></div>
</div>
</div>
The 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;
}
See it in action in this fiddle: http://jsfiddle.net/joplomacedo/T2PL5/
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