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

2020-01-24 02:44发布

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?

标签: css
17条回答
爷的心禁止访问
2楼-- · 2020-01-24 03:07

If you want to fix it on the right, for example, use justify-content: flex-end.

More: http://www.w3schools.com/cssref/css3_pr_justify-content.asp

查看更多
在下西门庆
3楼-- · 2020-01-24 03:08

Yes, You actually can do that only by using CSS...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

Tell me if it works

查看更多
Animai°情兽
4楼-- · 2020-01-24 03:10

I stumbled on this post looking for a nice way to keep my header/navigation bar centered and responsive to size changes.

//CSS
.nav-container {
  height: 60px;  /*The static height*/
  width: 100%;  /*Makes it responsive to resizing the browser*/
  position: fixed;  /*So that it will always be in the center*/
}

//jQuery
$(window).scroll(() => {
  if ($(document).scrollTop() < 60) {
    $('.nav-container').css('top', $(document).scrollTop() * -1)
  }
})

As we scroll, the bar moves upwards off the screen. If you scroll left/right it will stay fixed.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-01-24 03:12

On parent div you can add

overflow-y: scroll; 
overflow-x: hidden;
查看更多
叛逆
6楼-- · 2020-01-24 03:13

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

查看更多
登录 后发表回答