6

I want to calculate the width of the scrollbar so that I use the result in a CSS calc() declaration.

At the moment, I assume that the width of the scrollbar is always 17px, like this:

body { 
    width:calc(100vw - 17px); 
}
.container { 
    max-width:calc(100vw - 17px); 
}

The problem with this is when you choose a different browser zoom %, the width of the scrollbar changes. So I want to use the result of the calculation to do something along these lines:

body { 
    width:calc(100vw - CALCULATED SCROLL-BAR WIDTH); 
}
.container { 
    max-width:calc(100vw - CALCULATED SCROLL-BAR WIDTH); 
}

EDIT: I've now solved the problem with the help of this question

The JavaScript used to calculate the scrollbar width (though, I have found you require an interval to get it to autoupdate):

function getScrollbarWidth() {
  var outer = document.createElement("div");
  outer.style.visibility = "hidden";
  outer.style.width = "100px";
  outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

  document.body.appendChild(outer);

  var widthNoScroll = outer.offsetWidth;
  // force scrollbars
  outer.style.overflow = "scroll";

  // add innerdiv
  var inner = document.createElement("div");
  inner.style.width = "100%";
  outer.appendChild(inner);        

  var widthWithScroll = inner.offsetWidth;

  // remove divs
  outer.parentNode.removeChild(outer);

  return widthNoScroll - widthWithScroll;
}

My code (which is used to embed the result of the function into a CSS calc() declaration).

$('body').css({ 
  'width':'calc(100vw - ' + getScrollbarWidth() + 'px)' 
});

$('.container').css({ 
  'max-width':'calc(100vw - ' + getScrollbarWidth() + 'px)' 
});
Community
  • 1
  • 1
Bailey280899
  • 81
  • 1
  • 4

2 Answers2

11

Actually, you can get the scrollbar width just with css and custom properties (and completely without javascript):

body {
    --scrollbar-width: calc(100vw - 100%);
}

Then you can use this variable in a child element like this:

.container { 
    max-width: calc(100vw - var(--scrollbar-width)); 
}

This is because 100vw is always the inner width of the view, but the 100% of the body does not include the scrollbar.

jonas_jonas
  • 306
  • 3
  • 7
1

Why you need so much code to do that?

The easy way with plain javascript it's:

$('body').css({ 
  'width':'calc(100vw - ' + (window.innerWidth - document.body.clientWidth) + 'px)' 
});
NetVicious
  • 3,258
  • 1
  • 29
  • 44