Mushex Antaranian Mushex Antaranian - 1 year ago 64
Javascript Question

jQuery .position() strangeness while using CSS3 rotate attribute

I'm getting absolutely positioned rotated elements position with jQuery

method, then setting position-related attributes (top, left) with jQuery
, where
is the data returned by
. I think it'll leave the element in it's place, but elements position is changing.

How can I use set rotated elements position, so that it'll be placed as expected? Maybe there is a coefficient depended on angle that changes position?

I'm testing in Google Chrome v.9, Windows XP.


<div id="container">
<div id="element">
<img src=""/>


#container {
position: relative;
border: 1px solid #999;
padding: 5px;
height: 300px;
#element {
position: absolute;
left: 60px;
width: auto;
border: 1px solid #999;
padding: 5px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);


var $el = $('#element'),
// getting position
pos = $el.position();
alert(pos.left + '/' +;
// alerts 37/11

// setting css position attributes equal to pos
// re-getting position
pos = $el.position();
alert(pos.left + '/' +;
// alerts 14/-28

View it

Answer Source
// Needed to read the "real" position
$.fn.adjustedPosition = function() {
    var p = $(this).position();
    return {
        left: p.left -'dx'),
        top: -'dy')

$(function() { 

    var img = $('img'),

    // Calculate the delta
    img.each(function() {
        var po = $(this).position(), // original position
            pr = $(this).addClass('rot').position(); // rotated position

            dx: pr.left - po.left, // delta X
            dy: - // delta Y

    // Read the position
    pos = img.adjustedPosition();    
    alert(pos.left + '/' +;     

    // Write the position

    // Read the position again
    pos = img.adjustedPosition();    
    alert(pos.left + '/' +;


Live demo:

So what is going on here:

  1. The CSS code that rotates the image is stored inside a special CSS class. I do this because I want to read the original position of the image (before rotating). Once I read that original position, I apply the .rot class, and then read the position again to calculate the difference (delta), which is stored inside the element's data().

  2. Now, I can read the position via the custom method adjustedPosition (which is defined above). This method will read the position of the element and then subtract the delta values stored inside the data() of the element.

  3. To write the position, just use the css(pos) method like normally.