Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content jumps horizontally whenever browser adds a scrollbar

I'm using a fixed width body and auto margins to center my content in the middle of the page. When the content exceeds the page's height and the browser adds a scrollbar, the auto margins force the content to jump half the width of the scrollbar left.

Is comparing outerHeight with window.innerHeight an appropriate way of solving this? Is there another way to solve this?

I think this should be enough info for the problem, but let me know if I can answer anything else.

Edit for clarification: I don't want to force the scrollbar to appear.

like image 998
Nick Bergseng Avatar asked Feb 08 '12 21:02

Nick Bergseng


2 Answers

I'll just leave this link here because it seems an elegant solution to me:

https://aykevl.nl/2014/09/fix-jumping-scrollbar

What he does is add this css:

@media screen and (min-width: 960px) {
    html {
        margin-left: calc(100vw - 100%);
        margin-right: 0;
    }
}

This will move the content to the left just the size of the scrollbar, so when it appears the content is already moved. This works for centered content with overflow: auto; applied to the html tag. The media query disables this for mobile phones, as its very obvious the difference in margin widths.

You can see an example here:

http://codepen.io/anon/pen/NPgbKP

like image 94
xabitrigo Avatar answered Oct 18 '22 00:10

xabitrigo


I've run into this problem myself and I've found two ways to solve it:

  1. Always force the scrollbar to be present: body { overflow-y: scroll; } Setting it on the html doesn't work in all browsers or might give double scroll bars if the scrollbar does appear.

  2. Add a class that adds ~30 pixels to the right margin of your page if there is no scrollbar.

I've chosen option 1 but I'm not sure if it works in all browsers (especially the older ones).

Facebook uses option 2.

like image 7
Halcyon Avatar answered Oct 17 '22 23:10

Halcyon