Hello guys I am trying to make a sticky sidebar but it isn't working how I want it to work. Any help would be much appreciated. What happens when you scroll is that the sidebar gets thrown out of his left position. As you can see in the fiddle the same happens only here I am using an image. Here is a Js fiddle . Any ideas what I am doing wrong or how I can make this work?
Thanks in advance!
jQuery code
jQuery(function() { // document ready
var sideBarTop = $('#sidebar').offset().top;
var sideBarLeft = $('#sidebar').offset().left
jQuery(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop();
if(sideBarTop < windowTop) {
$('#sidebar').css({position: 'fixed', top: 0, left: sideBarLeft});
}
else {
$('#sidebar').css('position', 'static');
}
});
});
This issue is due to the percentage value you've set on the #sidebar
. When it's static the percentage value will be based on its parent element however when you switch to position:fixed
the percentages will be based on the window/viewport
, you can see the spec here: http://www.w3.org/TR/CSS2/visuren.html#positioning-scheme
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.