Alex Rivera | Logout

Prevent a centered layout from shifting its position when scrollbar appears

Asked 2012-02-18T13:12:23.910
42

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?

Edit
Report

1 Answer

0

If you can use Javascript, you can set the width of the content-wrap to the inner width of the window minus the standard width of a scrollbar.

You will run into some problems though.

  • The user will have to have Javascript enabled
  • You don't know what the width of the vertical scrollbar is, especially if the scrollbar isn't there! So you will have to guess. 20px seems like a good guess.
  • Different browsers have different ways of telling you want the inner width of the window is.

So if you can live with all that, you can do something like this (in pseudo code)

if window.innerWidth is defined :
   set the width of the div to window.innerWidth-20px
else if we're running on Internet Explorer :
   set the width to document.documentElement.offsetWidth-20px
otherwise :
   we're out of luck and we best leave the width as is.
answered 2012-02-18T15:25:37.927

Your Answer