Question

Simple scenario here: http://jsfiddle.net/s4tjP/1/

<style>
   #outer  { width: 200px; height: 100px; outline: solid 1px Red; }
   #inner { width: 220px; height: 120px; oultine: solid 1px Green;
             -webkit-transform: scale(0.75);
             -webkit-transform-origin: 50% 0;
   }
</style>

<div id="outer">
    <div id="inner"></div>      
</div>

The problem is how to calculate the x origin for a scaled object in order to centre it horizontally on it's parent object. All dimensions are known.

The fiddle shows the outer box with width 200px, and the inner box with width 220px, scaled 0.75 resulting in 165px.

An x-origin of 50% sets the origin half way along the unscaled object. That's obviously too much. So, should it not be 50% x the scale ratio (in this instance 37.5%) - but that's not right either. In pixels, half the difference between the sizes seemed like a good way to estimate it but no luck.

Thanks.

Was it helpful?

Solution

Well, this is more a mathematical problem than a programming one, isn't it.

To begin, you have an inner width of 220px inside a div of 200px, aligned left. Your offset is then 10px (half the difference). You need to move the center of the inner div 10px to the left to get it centered.

Then. you are applying a scale of 0.75. That means a delta (or change) of 0.25. To get a delta of 10px (the movement that you need), you have to apply it to 40px of initial length (10px divided by 0.25). If your transform is happening 40px to the left of the center of the inner div, it will center it.

Now, since the center is at 110px from the left edge, this point 40px to the left of the center is 70px to the right of the left edge.

And finally, 70px in a 220px width is 31.81 %.

Try it and you will see

OTHER TIPS

Brilliant, thank you @vals. Since the x-origin can be expressed in pixels, we can simplify thus:

x = outer width 
j = inner width 
s = scale 
k = js (scaled width)
d = 1-s (delta)

x-offset = (x-k) / 2d
x-offset = (outer width - (inner width * scale)) / 2 (1 - scale)

That's immensely useful (sorry @Paulie_D !)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top