1

I have a header div above a scrolling div and I'd like to pad the header on the right the same width as the scrollbar. I know I can use JavaScript to calculate the scrollbar width, but I was wondering if there's a pure CSS method to do this?

Edit

To complicate this more, if there are few results that come back so the scrolling div doesn't produce a scrollbar, then I'd want the header to not be padded as well. I'm not sure if that's possible using only CSS, but thought it's worth asking.

adam0101
  • 29,096
  • 21
  • 96
  • 174

2 Answers2

1

What about "forcing" an overflow-y:scroll then making it non-visible?

#myDiv{
  overflow-y:scroll;
}
#myDiv::-webkit-scrollbar {
  opacity:0;
}

A CodePen

I have to mention that I just had this idea...
You'll have to test it for browser compatibility.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • If it works, that would take care of the first part of my question, but then I still need a way for it to be applied conditionally if the div below has a scrollbar or not. – adam0101 Jun 15 '17 at 20:39
  • That absolutely need JS to be determined. – Louys Patrice Bessette Jun 15 '17 at 20:39
  • But to make a short answer... I would use [this other SO answer](https://stackoverflow.com/a/7139047/2159528) to determine if there is an overflow in the scrollable `div`... **And** my idea as a class to add/remove to the non-scrollable one. ;) Good luck| – Louys Patrice Bessette Jun 15 '17 at 20:49
  • 1
    For IE, I couldn't find a way to set the opacity, but I was able to set the color to match the background. After doing that, this worked well. Thanks. – adam0101 Jun 19 '17 at 16:04
0

It seems that all major browsers have the same width, no calculation necessary:

http://www.textfixer.com/tutorials/browser-scrollbar-width.php

Would it be acceptable to just put that in the CSS?

vbullinger
  • 4,016
  • 3
  • 27
  • 32
  • Please see my edit. It might be, but I'd still have to detect if there was a scrollbar or not so I know whether to pad the header or not. – adam0101 Jun 15 '17 at 20:34
  • Also, with possibly different zooming behavior or accessibility needs, I'm not sure I want to chance it. – adam0101 Jun 15 '17 at 20:45