Back to posts

Get window size in pure CSS

We all know that CSS it has become even harder nowadays. You wouldn't believe it, but CSS can define properties, do the math, and even directly get the window size!

TS
Thiago Saraiva
1 min read

Get Window Size With Css

Define Property

The @property rule is a new feature in CSS that allows developers to create custom properties and set their types, inheritance, and initial values. Using this feature, we can read specific values and pass them to custom properties. In the example below, we define two custom properties, --w_raw and --h_raw, representing the window's width and height respectively:

Removing Units

Now, we have obtained the window width and height values, but they still include units. How can we remove the units to get pure numeric values? It's a matter of math, so we need to use the mathematical tools in CSS: atan2(y, x) and tan(). Combining these, we can obtain the pure numeric values. Here, we pass var(--w_raw) and 1px as parameters to calculate the angle of the width and then convert it to a number. In this way, we convert the width and height to unitless values and store them in :root's variables.

Displaying the Numbers

Now that the numeric values are stored in CSS, how do we display them? It's the counter that counts!

Done!

Now you have a window size indicator implemented purely in CSS. The browser will update --w and --h in real time and display them on the page. The entire process is entirely JavaScript-free.