Get the width & height of any element without JavaScript
Use Scroll-Driven Animations and modern CSS features to get the width and height of any element without JavaScript. You get unitless pixel values as CSS variables that you can make available anywhere on the page.
@property --_x {syntax: "<number>";inherits: true;initial-value: 0;}
@property --_y {syntax: "<number>";inherits: true;initial-value: 0;}
.size {
overflow: auto;
position: relative;
--w: round(1/var(--_x)); /* element width */
--h: round(1/var(--_y)); /* element height */
timeline-scope: --cx,--cy;
animation: x linear,y linear;
animation-timeline: --cx,--cy;
animation-range: entry 100% exit 100%;
}
.size:before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 1px;
aspect-ratio: 1;
view-timeline: --cx inline,--cy block;
}
@keyframes x {0% {--_x:1}}
@keyframes y {0% {--_y:1}}
Resize the below demo to see how the values update in real-time:
See the Pen Get width/height of elements using CSS by Temani Afif (@t_afif) on CodePen.
Here is the particular case of the screen sizes
See the Pen Get screen dimension using only CSS by Temani Afif (@t_afif) on CodePen.
More detail: frontendmasters.com/blog/how-to-get-the-width-height-of-any-element-in-only-css
More CSS Tips
- Arc shape with rounded edges a few lines of modern CSS to create an arc shape with rounded edges.
- Get the width of the scrollbar using only CSS Using modern CSS features to get the scrollbar width as a CSS variable.
- 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).