Home >Web Front-end >CSS Tutorial >How to Retrieve the True Width and Height of a Rotated Element in JavaScript?
Retrieving Width/Height After Rotation Transformation
When you apply a rotation transform to an element using CSS, the element's visual appearance may change, but the JavaScript properties for its width and height may not reflect this change.
Problem:
After applying a rotation transform of 45 degrees, a 11x11 square appears to be 17x17 in the browser. However, if you attempt to retrieve the width and height properties using JavaScript, you still get the original values (10x10).
Solution:
To accurately retrieve the width and height after applying a rotation transform, you can use the getBoundingClientRect() method of the HTMLDOMElement. This method returns an object with the correct height and width, taking into account the transformation matrix.
<code class="javascript">const element = document.querySelector('.rotated-element'); const rect = element.getBoundingClientRect(); const width = rect.width; const height = rect.height;</code>
This approach gives you the desired result (17x17) because getBoundingClientRect() takes into account the actual visual dimensions of the rotated element, not just the original values stored in the element's properties.
The above is the detailed content of How to Retrieve the True Width and Height of a Rotated Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!