Calculating Viewport Width (vw) Excluding Scrollbar in CSS
As mentioned in the original question, obtaining the viewport width (vw) without accounting for the scrollbar can be a challenge using CSS alone. However, there is a workaround involving the calc() function that can achieve this.
In calc(), 100% represents the viewport width including the scrollbar. By subtracting the difference between 100% and 100vw, you can effectively disregard the scrollbar width:
<code class="css">body { width: calc(100vw - (100vw - 100%)); }</code>
This expression assigns the body element a width equal to the vw minus the scrollbar width.
Additionally, this approach can be applied to any element, not just direct children of the body. For example, to create a square that occupies 50% of the viewport while excluding the scrollbar width:
<code class="css">.box { width: calc(50vw - ((100vw - 100%) / 2)); height: 0; padding-bottom: calc(50vw - ((100vw - 100%) / 2)); }</code>
The above is the detailed content of How to Calculate Viewport Width (vw) Excluding the Scrollbar in CSS?. For more information, please follow other related articles on the PHP Chinese website!