How to get an element's rect BEFORE a transform?

3.2k views Asked by At

Currently, Element.getBoundingClientRect() gives the position and dimensions of an element, but it automatically accounts for transformations via the CSS transform property. How can I get the rectangle without the transformation?

In the example below, I would want the output to be 10 10 100 100.

const rect = div.getBoundingClientRect()
document.write(`${rect.left} ${rect.top} ${rect.width} ${rect.height}`)
body {
    margin: 10px;
}

div {
    background: red;
    width: 100px;
    height: 100px;
    transform: translate(1px, 1px) scale(0.5)
}
<div id="div"></div>

1

There are 1 answers

0
Wenli He On

Here is already an answer, you can read more on this post: How do I retrieve an HTML element's actual width and height?

So, you can get the actual value "before" transform by changing your code to the following

document.write(`${div.offsetLeft} ${div.offsetTop} ${div.offsetWidth} ${div.offsetHeight}`)
body {
    margin: 10px;
}

div {
    background: red;
    width: 100px;
    height: 100px;
    transform: translate(1px, 1px) scale(0.5)
}
<div id="div"></div>