Get the width & height of any element without JavaScript
Use modern CSS features to get the width and height of any element as CSS variables.
- Powered by Scroll-Driven animations and
@property
- Unitless values so you can easily use them inside any formula
- You can apply the trick to multiple elements on the page
- You can make the variables available everywhere on the page
@property --_x {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
@property --_y {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
@property --w {
syntax: "<integer>";
inherits: true;
initial-value: 0;
}
@property --h {
syntax: "<integer>";
inherits: true;
initial-value: 0;
}
.size {
overflow: auto;
position: relative;
--w:calc(1/(1 - var(--_x))); /* element width */
--h:calc(1/(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 {to{--_x:1}}
@keyframes y {to{--_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