Is it possible to calculate the Viewport Width (vw) without scrollbar?

Marten Zander picture Marten Zander · Nov 9, 2015 · Viewed 60.3k times · Source

As mentioned in the title, is it possible to calculate the vw without the scrollbars in css only?

For example, my screen has a width of 1920px. vw returns 1920px, great. But my actual body width is only something like 1903px.

Is there a way for me to retrieve the 1903px value with css only (not only for direct children of the body), or do I absolutely need JavaScript for this?

Answer

Mattias Ottosson picture Mattias Ottosson · Jan 19, 2016

One way to do this is with calc. As far as i know, 100% is the width including scrollbars. So if you do:

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

You get the 100vw minus the width of the scrollbar.

You can do this with height as well, if you want a square that's 50% of the viewport for example (minus 50% of the scollbar width)

.box {
  width: calc(50vw - ((100vw - 100%)/2))
  height: 0
  padding-bottom: calc(50vw - ((100vw - 100%)/2))
}