Is it possible to calculate the Viewport Width (vw) without scrollbar?
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?
Solution 1:
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))
}
Solution 2:
I do this by adding a line of javascript to define a CSS variable once the document has loaded:
document.documentElement.style.setProperty('--scrollbar-width', (window.innerWidth - document.documentElement.clientWidth) + "px");
then in the CSS you can use var(--scrollbar-width)
to make any adjustments you need for different browsers with/without scrollbars of different widths. You can do something similar for the horizontal scrollbar, if needed, replacing the innerWidth
with innerHeight
and clientWidth
with clientHeight
.
Solution 3:
According to the specs, the viewport relative length units do not take scrollbars into account (and in fact, assume that they don't exist).
So whatever your intended behavior is, you cannot take scrollbars into account when using these units.