CSS Animation - Grow from center (Zoom from center dot to full container)

alexp2603 picture alexp2603 · Mar 6, 2017 · Viewed 40k times · Source

I'm working on a game and I want to animate some boxes.

I want a box to start from small and then grow outwards, with all edges growing at the same time in an effect that looks like it is growing outwards from the center.

The best animation I have so far is the following: it grows the height and the width of the box as I want, but starts from the left and top. I would like it to start from a center point.

I looked at the animation properties on W3 and nothing seems to fit the boat.

  .box_2_gen{
    
    animation-duration: 0.25s;
    animation-name: createBox;

    position: relative;

    background: #FFEDAD;

    border: black solid;
    border-width: 1px;
    border-radius: 15px;

    width: 98px;
    height: 98px;

    margin: 10px;

    float: left;
}



@keyframes createBox{
    from{
        height:0px;
        width: 0px;

    }
    to{
        height: 98px;
        width: 98px;
    }
}

EDIT: My question may seem like another similar one, but I just wanted to know how to do it using only keyframes.

Thanks, Alex

Answer

Michael Coker picture Michael Coker · Mar 6, 2017

You should use transform in the animation for better performance and more control. Then you won't have to repeat the static px values, and you can use transform-origin to control where the transform happens. scale() will scale from the center by default.

div {
  background: red;
  animation: createBox .25s;
  width: 98px; height: 98px;
}
@keyframes createBox {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}
<div></div>