4

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>
darrylyeo
  • 3,103
  • 20
  • 30
  • Why not remove the transform property, measure it, then add the property back again? – Jacob G Jan 03 '17 at 02:31
  • I considered doing that, but my gut tells me there should be a simpler way. I'd be pretty surprised if there wasn't a built-in for this. – darrylyeo Jan 03 '17 at 02:35
  • http://stackoverflow.com/questions/27745438/how-to-compute-getboundingclientrect-without-considering-transforms – Jacob G Jan 03 '17 at 02:38

1 Answers1

4

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>
Community
  • 1
  • 1
Wenli He
  • 333
  • 3
  • 9