Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: fixed position on x-axis but not y?

Tags:

css

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?

like image 460
kylex Avatar asked Jan 12 '10 15:01

kylex


People also ask

How do you stop the Y axis from scrolling in CSS?

Check out the website for a list of many examples; but yes, "overflow-y: hidden" will only hide vertical scroller.. if you were to use "overflow-x: scroll; overflow-y: hidden;" then this will only enable the x-axis and the y-axis is hidden.

How do I fix fixed position in CSS?

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.

What is the difference between sticky and fixed position in CSS?

1. Element with position: fixed property is fixed to the viewport and doesn't move irrespective of scrolling. Element with position: sticky property can scroll to an offset value provided by the user.

What is the opposite of position fixed in CSS?

position:static; , position:absolute; , and position:relative; are the alternatives to position:fixed; . There isn't a definitive opposite, because relative , absolute , static , and fixed have different properties to behave differently.


1 Answers

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 :)

like image 162
Starx Avatar answered Oct 04 '22 12:10

Starx