Skip to content
Advertisement

Why when I use transform scale it moves the animated div’s position

EDIT : I don’t think this question should be marked as a possible duplicate because It deals with distracting SVG info and I think unnecessary math.

In the keyframes section below when I leave out the transform: scale the div shows up in the middle of the page. That’s what I want. Now I wanted to make it so that the div start out bigger and the opacity fadesIn while the div gets smaller and the center of the div should be at the center of the page. When I add transform scale the div doesn’t animate in the center anymore. why? and how can I fix it?

   .popup{
        position: absolute;
        width:400px;
        height: 300px;
        left: 50%;
        top: 50%;
        background: limegreen;
        border: 5px solid silver;
        transform: translate(-50%, -50%);
        transition: all 2s;
        opacity: 0;

    }
    .anim{
        animation: popAnim 2s forwards;
    }
    @keyframes popAnim{
        0%{
            transform : scale(1.5);
            opacity: 0;
        }
        100%{
            transform: scale(1);
            opacity: 1;
        }
    }

html:

<div class="popup">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error inventore molestiae, dignissimos ducimus adipisci sint suscipit dolor blanditiis fugit, quia aspernatur quos, facere nostrum! Distinctio praesentium saepe, quaerat modi fuga.</div>
<button class="click">click me</button>

jquery:

$(document).ready( function(){
        $(".click").on("click", function(){
            $(".popup").toggleClass("anim")
        })
});

Advertisement

Answer

In declaraing transform : scale(1.5); you’re overriding transform: translate(-50%, -50%);, so transform: scale(1.5) is the equivalent of transform: translate(0, 0) scale(1.5).

Instead, you need to stack your transform values so the translate is maintained. The keyframe animation becomes:

  @keyframes popAnim{
    0%{
      transform : translate(-50%, -50%) scale(1.5);
      opacity: 0;
    }
    100%{
      transform: translate(-50%, -50%) scale(1);
      opacity: 1;
    }
  }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement