Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve width/height of a css3 scaled element

I'm fighting against an oddity (I think) of the offsetWidth property.
this is the scenario:

I've got, let's say, a span tag, in my js, at a certain point I perform a css3 transform to this element, like:

        el.set('styles', {             'transform':'scale('+scale+', '+scale+')',      /* As things would be in a normal world */             '-ms-transform':'scale('+scale+', '+scale+')',      /* IE 9 */             '-moz-transform':'scale('+scale+', '+scale+')',         /* Moz */             '-webkit-transform':'scale('+scale+', '+scale+')',  /* Safari / Chrome */             '-o-transform':'scale('+scale+')'       /* Oprah Winfrey */          });          w = el.getWidth();         console.log('after scaling: ' + w); 

at this point the log returns me fuzzy values, like it doesn't know what to say.
any suggestion?

like image 256
holographix Avatar asked Apr 29 '11 16:04

holographix


People also ask

How do I retrieve an HTML element's actual width and height?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

How do you find the width of an element in pixels?

To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth property of this HTML Element. clientWidth property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element.

What is scale () in CSS?

The scale() CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales. Its result is a <transform-function> data type.


2 Answers

getBoundingClientRect() returns the correct values for me.

jsFiddle.

like image 71
alex Avatar answered Sep 26 '22 05:09

alex


Transforms don't affect the intrinsic CSS properties, so you are seeing correct behavior. You need to look at the Current Transformation Matrix - as returned from getComputedStyle().webkitTransform in order to figure out how big something has been scaled.

Update: In Firefox 12 and later and Chrome/Safari - as Alex says below, you can use getBoundingClientRect() to take into account any transforms applied to an element

The scale transition starts from 50%/50% because that's the default & correct behavior. If you want it to start from the origin, then you need to set transform-origin: 0% 0%;

like image 21
Michael Mullany Avatar answered Sep 22 '22 05:09

Michael Mullany