0

Is it possible to (temporarily) hide the main window (vertical) scrollbar (the one on body/html) without (slightly) moving centered content?

Setting overflow: hidden on body, html hides the scrollbar but the centered content is moved half of the scrollbars width to the right when doing this. I could add padding-right: <width-of-scrollbar> but that varies, and also would move the content if there is no scrollbar to begin with.

Qtax
  • 33,241
  • 9
  • 83
  • 121
  • For this, one might need an `onShowScrollBar` or `onContentOverFlow` browser event, do these exist? – Marc Audet Apr 02 '13 at 10:45
  • 1
    If you `body` has default/empty `width` as style, you can try this: http://jsfiddle.net/9keQe/ – Passerby Apr 02 '13 at 10:59
  • FireFox see's the scrollbar diffrently than the other browsers so keep this in mind when you still see some changes trough FF – Matthias Wegtun Apr 02 '13 at 11:12
  • @Passerby, that could work in some cases. But the content width would't adjust to the window width when this is in effect. – Qtax Apr 02 '13 at 11:23
  • Related http://stackoverflow.com/questions/5605667/scrollbar-shifts-content – Qtax Apr 02 '13 at 11:53

1 Answers1

0

You could position the centered piece relatively (left: 50%) and use javascript to set the position fixed in pixels afterwards. In jQuery:

$(".centered").offset({left : $(".centered").offset().left});

See it in action here: http://jsfiddle.net/willemvb/jP3PK/4/

Willem Van Bockstal
  • 2,233
  • 1
  • 17
  • 24
  • Doing that would fix the position of the element when resizing the window. And you have to make the script aware of all centered elements, which isn't desired as I'm looking for a general solution as independent of content as possible. – Qtax Apr 02 '13 at 11:18
  • I think you will need scripting anyway if you would want to eliminate the scrollbar. So give every centered element the same class and call jQuery on this class. Afterwards $(window).resize would be your friend. The only non-js solution I heard of is the use of overflow-y: scroll on the html element, but this one shows the scrollbar area even if you cannot scroll the page. http://css-tricks.com/eliminate-jumps-in-horizontal-centering-by-forcing-a-scroll-bar/ – Willem Van Bockstal Apr 02 '13 at 13:13
  • Scripting - of course. Find and change every centered element on the page, no. That has many issues. And this solution wouldn't even work properly - eg. try to load your example with the width of the window/frame less than the width of the centered content. – Qtax Apr 02 '13 at 15:07
  • This solution can be adapted to support onresize, centered body instead of individual elements, body-width in %, max-width etc. http://jsfiddle.net/willemvb/jP3PK/4/ (not tested in IE...) – Willem Van Bockstal Apr 02 '13 at 16:27