How do I get the position of an element that uses the CSS transform property?

6

Imagine that I have a popup that is centered with transform:translateX(-50%) translateY(-50%) (if you have questions about this solution, you can see more about it here , adapted from these Answers ).

So far so good, the element is centralized correctly, but let's say for some reason I need to figure out the exact position of it in document of the browser (to implement a drag-and-drop by example). I tried the properties offsetTop and offsetLeft but they return the position of the element without the transforms, ie it is a "fake" position.

My question is, is there any property that returns the actual values of an element that is positioned using translate ?

Here is an example for a better understanding: FIDDLE .

    
asked by anonymous 13.03.2014 / 19:44

2 answers

7

As commented, the properties offsetTop and offsetLeft do not return the exact position of the element when it uses the translate() CSS property.

The only property I know that works with translate() is getBoundingClientRect() , and the most interesting: It is old and fully cross-browser (works up in IE6).

Here is an example implementation:

var el = document.getElementById('popup'),
    pos = el.getBoundingClientRect();

alert('Top: '+pos.top+'\nLeft: '+pos.left); // retorna a posição REAL do elemento

And an example: FIDDLE

    
13.03.2014 / 19:44
-1

When you use translate, the position of the element is centered.

This way you need to get the width of the element and divide by two, so you have the position left ;

To get the top , just get the height of the element and divide by two.

    
22.06.2017 / 21:50