Home >Web Front-end >CSS Tutorial >How to Get Accurate Width and Height of Transformed HTML Elements in JavaScript?
Determining Width and Height after Transformation
When applying transformations such as rotation to an HTML element, JavaScript's default methods may not accurately retrieve the transformed width and height.
Problem:
After applying a rotation transform (e.g., rotate(45deg)), the element may appear to have different dimensions (e.g., a square appears as a rectangle). However, JavaScript properties like width and height still return the original untransformed values.
Solution:
To retrieve the true dimensions after transformation, use the getBoundingClientRect() method on the HTMLDOMElement.
<code class="javascript">const element = document.getElementById('element'); // Apply the transformation element.style.transform = 'rotate(45deg)'; // Get the transformed dimensions const dimensions = element.getBoundingClientRect(); console.log('Transformed Width:', dimensions.width); console.log('Transformed Height:', dimensions.height);</code>
This method returns an object containing the element's dimensions after taking into account the transformation matrix.
Example:
A 11x11 square after a 45-degree rotation becomes a 17x17 rectangle in Chrome. The getBoundingClientRect() method accurately reports the 17x17 dimensions, while the original width and height properties still return 11x11.
The above is the detailed content of How to Get Accurate Width and Height of Transformed HTML Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!