Prevent a centered layout from shifting its position when scrollbar appears

前端 未结 6 1312
灰色年华
灰色年华 2020-12-03 05:05

My page layout looks something like this:



6条回答
  •  伪装坚强ぢ
    2020-12-03 05:41

    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.

提交回复
热议问题