Home  >  Article  >  Web Front-end  >  Can We Calculate Viewport Width Without Scrollbars in CSS?

Can We Calculate Viewport Width Without Scrollbars in CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 09:27:02763browse

Can We Calculate Viewport Width Without Scrollbars in CSS?

Calculating Viewport Width Without Scrollbars in CSS

Question: Can we determine the viewport width (vw) excluding scrollbars using solely CSS?

Answer: Yes, it is possible to calculate the vw without accounting for scrollbars using CSS. One method employs the calc() function to subtract the scrollbar width from the viewport width.

<code class="css">body {
  width: calc(100vw - (100vw - 100%));
}</code>

In this code, 100vw represents the full viewport width, and 100% represents the viewport width without scrollbars. The (100vw - 100%) term effectively calculates the scrollbar width, which is then subtracted from 100vw.

Additional Note: This technique can also be applied to calculate the height of a square that occupies half of the viewport width, 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 Can We Calculate Viewport Width Without Scrollbars in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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