I found this technic on https://frontendmasters.com/blog/how-to-get-the-width-height-of-any-element-in-only-css/ – it only works on modern browsers (mainly Chrome and Edge)
Let’s define the properties:
@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; }
Then, let’s find an element that is a common parent for both the element where we’ll calculate the height/width, and the element that will use this height/width, and we apply some CSS:
.parent { timeline-scope: --cx,--cy; --w:calc(1/(1 - var(--_x))); --h:calc(1/(1 - var(--_y))); animation: x linear,y linear; animation-timeline: --cx,--cy !important; animation-range: entry 100% exit 100%; }
We finish up with some additional CSS:
.get-dimension { overflow: hidden; position: relative; } .get-dimension: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}}
And finally, we can use --w
and --h
in the other element:
.apply-dimension { height: calc(var(--h)*1px); width: calc(var(--w)*1px); }
Here is a demo: