Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a centered layout from shifting its position when scrollbar appears

Tags:

html

css

scroll

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?

like image 383
Salman A Avatar asked Feb 18 '12 13:02

Salman A


People also ask

How can we make sure that a page doesn't display a horizontal scroll bar when it loads?

To hide the horizontal scrollbar and prevent horizontal scrolling, use overflow-x: hidden: HTML. CSS.

How do I stop the scroll bar from moving in CSS?

The easy fix is to use width: 100% instead. Percentages don't include the width of the scrollbar, so will automatically fit. If you can't do that, or you're setting the width on another element, add overflow-x: hidden or overflow: hidden to the surrounding element to prevent the scrollbar.

How do I stop horizontal scrolling in web design?

You can also set the overflow-x CSS property to hidden, which prevents child content from wrapping within its container but turns off sideways scrolling. Another solution is to set the width of child elements to 100%.


1 Answers

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.

like image 200
Christofer Eliasson Avatar answered Sep 29 '22 20:09

Christofer Eliasson