
Get the width & height of any element without JavaScript
7/26/24About 2 minCSSArticle(s)blogcss-tip.comcss
Get the width & height of any element without JavaScript 관련
CSS > Article(s)
Article(s)

Get the width & height of any element without JavaScript
Using modern CSS to get the size of any element as CSS variables
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 Get width/height of elements using CSS by t_afif on CodePen.
Here is the particular case of the screen sizes
See Get screen dimension using only CSS by t_afif on CodePen.
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. July 31, 2024
- Calculate the scroll progress of the page A few lines of CSS to get the scroll progress of the page inside a CSS variable. July 23, 2024
- Manual typography using Scroll-driven animations Use a range slider to manually adjust the font-size of your website (100% CSS). July 18, 2024

Get the width & height of any element without JavaScript
Using modern CSS to get the size of any element as CSS variables