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

Can CSS Calculate Viewport Width Without Scrollbars?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 22:12:02262browse

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%));
}

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))
}

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!

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