Get Real-time Screen Size With Pure CSS: No JavaScript Needed

Category: CSS & CSS3 , Layout | September 11, 2024
Author:css-tip
Views Total:174 views
Official Page:Go to website
Last Update:September 11, 2024
License:Unknown

Preview:

Get Real-time Screen Size With Pure CSS: No JavaScript Needed

Description:

I recently came across a clever CSS technique from css-tip that lets you capture the actual width and height of the browser window using only CSS.

While JavaScript libraries often handle this task, this approach offers a way to get real-time screen dimensions without relying on JavaScript. Even when you resize the browser window, the size values update instantly.

The CSS technique works across different devices and browsers. It provides front-end developers with a simple way to create size-aware components and layouts.

How to use it:

1. Insert the following CSS code into your document or stylesheet:

@property --_w {
  syntax: '<length>';
  inherits: true;
  initial-value: 100vw; 
}
@property --_h {
  syntax: '<length>';
  inherits: true;
  initial-value: 100vh; 
}
:root {
  --w: tan(atan2(var(--_w),1px));
  --h: tan(atan2(var(--_h),1px)); 
}

2. Then you can display the real-time screen size in the element you specify.

<h2>Current Screen Size:</h2>
h2:before {
  content: counter(w) "x" counter(h);
  counter-reset: h var(--h) w var(--w);
}

How it works:

This CSS technique utilize the CSS @property rule to define two custom properties, --_w and --_h, which initially represent the viewport width (vw) and height (vh).

Then, using the atan2 and tan trigonometric functions, we calculate the actual screen width and height and store them in the --w and --h properties at the root level. The results are unitless integer values.

Finally, we use CSS counters to display these values. The h2:before rule inserts content before the h2 element, using the counter() function to display the values of the w and h counters. These counters are reset using the calculated screen width and height.

See Also:

You Might Be Interested In:


Leave a Reply