August 1, 2012
CSS: fixed position on x-axis but not y?
Question by kylex
Is there a way to fix a position on the x-axis only? So when a user scrolls up, the div tag will scroll up with it, but not side to side?
Answer by Starx
Its a simple technique using the script also. You can check a demo here too.
JQuery
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + 15
//Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
});
});
CSS
#header {
top: 15px;
left: 15px;
position: absolute;
}
Update Credit: @PierredeLESPINAY
As commented, to make the script support the changes in the css without having to recode them in the script. You can use the following.
var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + leftOffset //Use it later
});
});
Demo 🙂