Avoid scroll bar moving effect

The default overflow property for the html tag is ‘auto’ which display a scroll bar only when needed.

If for example you have a very short page, like the home page of this website, and your other pages are longer, you might have noticed that your website is moved to the left to live the space when a scroll bar is needed. In fact it is the center of the page that change because the sroll bar is not included in the width of the viewport. So if you use the trick margin:auto + fixed width, your navigator move the website to keep it centered as requested by your css.

Of course that will depend of the resolution of your client screen and your navigator but in most case that is what you get. Fortunatly the solution is really simple.

As far as I know, the scroll bars are contained in the html element of your page. The idea is to always display a vertical scroll bar so the centre of the page is always at the same place. We will use the css “overflow” property, used to set the container behavior when his content overflow it.

Theire is fourt possible values:

overflow : visible, the content is displayed outside the container

overflow : hidden, the content is clipped by the limit of the container

overflow : scroll, scroll bars are displayed in the container even if the content doen’t overflow the container

overflow : auto, scroll bars are displayed only if needed

Those property can be used with ‘overfow’, ‘overflow-y’ and overflow-x.

In our case we want a scroll bar on the y axis of the html element:

html{ overflow-y : scroll; }

And that’s it, your navigator will always display a vertical scroll bar, preventing the website to moving if you hadn’t.

3 Responses to “Avoid scroll bar moving effect”

  1. CSS Reset, how to start from the same base | Your Site Is Valid

    [...] because I like the original style of them. I have also added the trick to manage the scroll bar (See Avoid scroll bar moving effect for more details). I have taken off the part on blockquote as I try to stay away from using CSS to [...]

  2. Henrik Nordvik

    Thank you!

  3. Mikkel

    Perfect!

    Thank you very much :D

Leave a reply