How to Calculate Viewport Width (vw) Excluding the Scrollbar in CSS?

Linda Hamilton
Release: 2024-11-06 03:13:02
Original
362 people have browsed it

How to Calculate Viewport Width (vw) Excluding the Scrollbar in CSS?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template