Search code examples
javascriptjquerycsspositionscale

Calculate topmost position of a CSS3 scaled box within another box


This is a tricky one.

I need to find a way to calculate the correct position to align a box within another box at its top. However, there is CSS3 scaled content inside the inner box (the scale factor is known) so a basic based-on-top (0px) approach won't work.

As this is literally impossible to properly describe, see my jsFiddle here:

http://jsfiddle.net/gPyqS/a

Thank You!


Solution

  • You're going to have to get your math hands dirty here. The basic approach will be:

    1. Get the offset of the element
    2. Get the scale factor of the element
    3. Get the height of the element
    4. Get the Y component of the element's transformation origin
    5. Consider a transform origin of -(box height / 2) to be 0, and a transform origin of +(box height / 2) to be 1. Given those constraints, perform linear interpolation using the current Y origin to determine the scale factor to apply to the top edge.
    6. Multiply (box height / 2) by the value you derived in step 5, and subtract it from the Y offset you got in step 1. This is the visual offset of the top edge of the box.