Search code examples
jquerycssscalecss-transformsdisplay

Div inline-block display and proper position after using transform: scale


At the beginning I'd like to say sorry for my english - I'm trying to do my best ;)

Here is what I managed to create:

JSFiddle

What I'm trying to do is to scale div that contains few different elements by using js, but at the same time I do want to keep the inline-block display, so after scaling more (or less, depending ont the scale value) elements could fit in one row.

Html of just one element looks like this:

<div class="containerofelements">
 <div class="resizeratio">1</div>
 <div class="resizeratio">0.75</div>
 <div class="resizeratio">0.5</div>
 <hr />
 <div class="elements" style="background-image: url(https://image.ibb.co/ha1wAo/back.png)">
   <div class="middle">middle</div>
   <div class="leftup">leftup</div>
   <div class="rightup"><img src="https://image.ibb.co/dK2BRT/profile_default_m.jpg" /></div>
   <div class="leftdown">leftdown</div>
   <div class="rightdown">rightdown</div>
 </div>
</div>

The ammount of elements will be variable, and most likely there will be more different content inside the ".elements" div. The .resizeratio divs are buttons that scales .elements by the written value by using jquery.

I was able to successfully scale elements and keep position of all child elements by js by using code:

css({
 transform: "scale("+scale+")"
});

Unfortunately, after scaling the div does keep original position. As I managed to notice, the div itself is scaled, but it somehow does not change position, just like the empty space after scaling element down is filled by additional margin. How to prevent this?


Solution

  • Here is a quick fix for you

    JSFiddle

    Just add a div (for example .wrap) around .elements and change its width and height depending on scale like this.

    el.parent('.wrap').css({
      width: (350 * scale) + "px",
      height: (500 * scale) + "px"
    });
    
    .wrap {
      width: 350px;
      height: 500px;
      display: inline-block;
      position: relative;
    }
    
    .elements {
      width: 340px;
      height: 490px;
      background-repeat: no-repeat;
      margin: 5px;
      -moz-transform-origin: 0 0;
      transform-origin: 0 0;
    }