Home > Web Front-end > CSS Tutorial > Can CSS Calculate Viewport Width Without Scrollbars?

Can CSS Calculate Viewport Width Without Scrollbars?

Patricia Arquette
Release: 2024-11-06 22:12:02
Original
334 people have browsed it

Can CSS Calculate Viewport Width Without Scrollbars?

Measuring Viewport Width Without Scrollbars Using CSS

Can CSS be utilized to calculate the viewport width (vw) without including the scrollbar?

Various users experience discrepancies between the vw value and the actual body width, which excludes scrollbars. For instance, while the screen resolution might be 1920px, the vw returns 1920px, despite the body width being closer to 1903px.

The key lies in understanding that 100% width in CSS encompasses both the viewport and scrollbar. To isolate the viewport width, the following calculation can be employed:

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

This calculation subtracts the scrollbar width from the entire viewport width, effectively providing the desired width without scrollbars.

Furthermore, this technique can be extended to height measurements. For instance, to create a square element that occupies 50% of the viewport while excluding the scrollbar, the following code can be used:

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

The above is the detailed content of Can CSS Calculate Viewport Width Without Scrollbars?. 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