CSS - How to make a relative element follow me up and down but not left and right?

萝らか妹 提交于 2019-12-12 16:45:59

问题


I have a parent div with a fixed position and inside of that div I have the main div with a relative position. While I scroll the bar up and down it follows me (this I want) but I don't want it to follow me when I scroll the bar left to right (or right to left).

HTML:

<div id="wrapper">
   <div id="icons">
      icons
   </div>
</div

CSS:

#wrapper {
    position: fixed;
    z-index: 1000;
    top: 155px;
}
#icons  {
    width: 42px;
    position: relative;
    left: -67px;
}

Thank you!!


回答1:


You basically have to changed the left value of #wrapper based off of its initial position and the current $(document).scrollLeft() value:

var initSL = $(document).scrollLeft(),
    initOL = $('#wrapper').offset().left;

$(document).scroll(function(e){
    $('#wrapper').css('left', initOL - ($(document).scrollLeft() - initSL));
});

See example →




回答2:


No need to get JS or jQuery involved. I slightly modified the former answer to use only html and css

Position:fixed;

http://jsfiddle.net/z52qG/11/



来源:https://stackoverflow.com/questions/5643096/css-how-to-make-a-relative-element-follow-me-up-and-down-but-not-left-and-righ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!