Prevent a centered layout from shifting its position when scrollbar appears

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.

Leave a Comment