Skip to main content
CSS Tip

Get the screen width & height without JavaScript

Get the screen width and height as pixel values using a simple CSS code.

: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