Getting the size of a CSS3 transformed element

Problem

I'd like to retrieve the size of a div that I've applied a CSS3 transform to.

-webkit-transform: scale3d(0.3, 0.3, 1);

So, effectively I've made the element 30% of its original size. However, when I query the elements width/height it reports the size of the element before the transform was applied.

I understand that this is actually the correct behaviour and that the element doesn't actually change size but its content does. But, and the reason I'm asking on here, if I do a right click on the element and select "inspect element" from the pop-up menu (I'm using Safari on a Mac just now) the element is highlighted and the rendered size is presented in the browser tooltip attached to the element.

So, this suggests that the browser 'knows' the rendered size but I haven't found a way of accessing this information yet. Can anyone help me?

Problem courtesy of: swervo

Solution

Wow, this was trickier than I expected. I'm as surprised as you that there isn't an easy way.

Here is a proof of concept.

Here is the JS:

$('div').each(function() {
    var matrix = window.getComputedStyle(this).webkitTransform,
        data;
    if (matrix != 'none') {
        data = matrix.split('(')[1].split(')')[0].split(',');
    } else {
        data = [1,null,null,1];
    }
    $(this).text($(this).width() * data[0] + 'x' + $(this).height() * data[3]);
});

The key is the getComputedStyle() function which obnoxiously returns a matrix as a String that must be parsed into an array before it's useful. However it contains the rendered transform ratios which can be multiplied by the CSS dimensions to get the rendered size.

Reference: CSS Tricks

Solution courtesy of: Ansel Santosa

Discussion

You can use the getBoundingClientRect() method on elements to get the dimensions. It takes into account the transformation matrix (so you don't need to do any maths yourself).

var elementDimensions = element.getBoundingClientRect();

jsFiddle.

Discussion courtesy of: alex

This recipe can be found in it's original form on Stack Over Flow.