Get the screen width & height without JavaScript
Get the screen width and height as pixel values using a simple CSS code.
- Unitless values so you can easily use them inside any formula
- Updates on screen resize (No need for JavaScript)
:root {
--w: calc(100vw/1px); /* screen width */
--h: calc(100vh/1px); /* screen height */
/* The result is an integer without a unit! */
}
Resize the demo below to see how the values update in real-time:
See the Pen Screen width/height (CSS-only) by Temani Afif (@t_afif) on CodePen.
You can also get the width/height of any element using a different method
Another method with better support:
@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)); /* screen width */
--h: tan(atan2(var(--_h),1px)); /* screen height */
/* The result is an integer without unit */
}
See the Pen Screen width/Screen height (CSS-only) by Temani Afif (@t_afif) on CodePen.
More detail: dev.to/janeori/css-type-casting-to-numeric-tanatan2-scalars-582j
More CSS Tips
- Calculate the scroll progress of the page A few lines of CSS to get the scroll progress of the page inside a CSS variable.
- Manual typography using Scroll-driven animations Use a range slider to manually adjust the font-size of your website (100% CSS).
- Inverted border-radius using CSS mask One property and 4 gradients to invert the corner of any element with a radius.
- Circular progress using scroll-driven animations Transforming the native progress element into a circular one using scroll-driven animations.