Html – Prevent a centered layout from shifting its position when scrollbar appears

csshtmlscroll

My page layout looks something like this:

<style type="text/css">
#content-wrap
{
    margin: 0 auto;
    width: 800px;
}
</style>

<div id="content-wrap">
</div>

You'll notice that the content-wrap div shifts its position a tad bit when the vertical scrollbar appears. One scenario is when the browser starts to progressively render the page without displaying the vertical scrollbar, then determines that a scrollbar is needed because the content is taller than the "fold". This shifts the div about 10px towards left.

What is the best way to tackle this problem without forcing the browser to always display the scrollbar?

Best Answer

I'm afraid the best way to solve this is to force the scroll bar to be visible at all times with html {overflow-y: scroll;}. The problem you have is that the "available area" shrinks with say 10 px when the scroll bar appear. This cause the calculated margin on your left side to shrink with half the width of the scroll bar, thus shifting the centered content somewhat to the left.

A possible solution might be to calculate the margin with JavaScript instead of using margin: 0 auto; and somehow compensate for the "lost" pixels when the scroll bar appear, but I'm afraid it will be messy and the content will probably move a little bit anyway while you calculate and apply the new margin.