Search code examples
javascriptcsstransformscale

Calculate css translate property value on scale dynamically


I am trying to scale(X) the child div element to fit the parent div on window resize. I calculated the scale ratio by dividing the parent width and child width, and it works perfectly.

But alignment is not proper. Initially i set my child div margin-left 50 px from the parent div. Its not maintained on the scale.

This is the HTML/css code

#wrap {
    margin-left:50px;
    width:300px;
    height:300px
}
#parentDiv {
    width:500px
        height:300px;
}

    <body>
        <div id="parentDiv">
        <div id="wrap">           
            <img id="image" width="300px" src="http://placekitten.com/640/480" />
        </div>
        </div>      
    </body>

And this is the js code to scale on resize

 window.onresize = function() {
    scaleDiv();
  };

scaleDiv = function() {
    parentWidth = $('#parentDiv').width();
    scale = (parentWidth) / $('#wrap').width();
    new_width = $('#wrap').width() *     scale;
    $('#wrap').css('-webkit-transform', ' scaleX(' + scale + ')');
}

After some googling, i came to know that i can use translateX property to keep the alignment as original. But i am struck at how to calculate the translate value.

  $('#wrap').css('-webkit-transform', 'translateX(20%)' + ' scaleX(' + scale + ')');

i put random value 20% on translate prop, its not proper. Can someone help me how to caclulate this value propery.

This is the jsfiddle test link


Solution

  • You need to specify the transform origin; by default this is set to 50% and 0%, but you can override it with the transform-origin property like so:

    #wrap {
        -webkit-transform-origin:0 0;
        -moz-transform-origin:0 0;
        -ms-transform-origin:0 0;
        transform-origin:0 0;
    }