Home >Web Front-end >CSS Tutorial >How to Get the Accurate Width and Height of a Transformed Element in JavaScript?
Retrieving Width and Height After Transformation
When applying a transform such as rotate(45deg) to an element, the visual dimensions of that element change. However, the width and height properties in JavaScript still reflect the original untransformed dimensions.
Solution: Using getBoundingClientRect()
To obtain the updated dimensions after transformation, use the getBoundingClientRect() method on the HTMLDOMElement. This method returns an object containing the transformed height and width.
Example:
<code class="javascript">// Get the element const element = document.querySelector('.transformed'); // Calculate the rotated dimensions const rect = element.getBoundingClientRect(); // Access the rotated width and height const rotatedWidth = rect.width; const rotatedHeight = rect.height;</code>
Demo:
Visit this jsFiddle for a practical example: https://jsfiddle.net/your_url_here
Note: This method will give you the dimensions of the entire element, including any borders or padding. If you need to calculate the content dimensions only, you should use offsetWidth and offsetHeight on the element's content element (e.g.,
The above is the detailed content of How to Get the Accurate Width and Height of a Transformed Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!