How to scale from right to left in CSS?

2020-07-25 01:08发布

问题:

I'm trying to animate scale a div element. But the animation starts from the center and spreads. Is it there a way animation to start from right and spread to left?

.graybox {
  float: right;
  background-color: gray;
  height: 100px;
  width: 400px;
  line-height: 100px;
  -webkit-animation: main 250ms;
  -moz-animation: main 250ms;
  -ms-animation: main 250ms;
  animation: main 250ms;
}

@-moz-keyframes main {
  0% {
    -moz-transform: scaleX(0);
  }
  100% {
    -moz-transform: scaleX(1);
  }
}

回答1:

By default the transform-origin is 50% 50%, you can reset that to 100% 50%, the first value 100% is x-offset, and the second value 50% is y-offset.

To make the div to scale for both width and height, simply change scaleX to scale.

You also need to set the correct @keyframes syntax, -moz prefix will only work on Mozilla browsers like Firefox. I suggest to use autoprefixer for adding popular prefixes.

.graybox {
  float: right;
  background-color: gray;
  width: 100%;
  height: 100px;
  line-height: 100px;
  animation: main 3s;
  transform-origin: 100% 50%;
}

@keyframes main {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}
<div class="graybox"></div>



回答2:

Use transform-origin

.graybox {
  float: right;
  background-color: gray;
  height: 100px;
  width: 400px;
  line-height: 100px;
  transform-origin: 100% 50%;
  animation: main .5s;
}

@keyframes main {
  0% {
    transform: scaleX(0);
  }
  100% {
    transform: scaleX(1);
  }
}
<div class="graybox"></div>