简体   繁体   中英

CSS3 transition: tilt/rotate slightly while moving, then restore to horizontal

Is it possible, using CSS transitions, to tilt (rotate) an element slightly off-horizontal during the first half of its movement--and tilt it back to horizontal during the second half, as it reaches the end of its movement? I don't want a 360-degree spin. Just a slight tilt, then tilt back again.

Here's a picture of the beginning, middle, and end of the transition I have in mind:

运动中倾斜

This question is best demonstrated by watching it. Here's a fiddle that shows what I would like to achieve--but I'd like to achieve it with CSS transitions, not JavaScript:

http://jsfiddle.net/bmorearty/S5Us6/22/

When you run this, watch the gray box closely. It tilts a bit during motion, then reverses its tilt halfway through--so when it comes to rest, it is no longer tilted.

I would like whole motion this to happen in a single transition from one state to another simply by adding a class to an element--not in two transitions, because that would require me to time the end of one with the beginning of the next.

I suspect the answer would incorporate transition-delay and/or @keyframes .

Thanks.

You could do something like this. http://cdpn.io/sIxFA

Obviously, you could smooth out the rotation as you please, and add the rotate class on click.

this would be the css for it:

#card {
    padding: 2em;
    border: 1px solid gray;
    display: inline-block;
    position: relative;
    background-color: #eee;
    /*instead of infinite you can add a number of times you want it running*/
    animation: moving infinite 6s;

}
@keyframes moving {
    0%{
      margin: 0;
    }
  50% {
 -webkit-transform: rotate(45deg);
  }
  100% {
    margin: 50px;
    }
}

I got it!

The solution is to use a CSS animation with a keyframe that transforms the rotation (eg, to about 8deg) when it is 50% of the way through, but returns the rotation to 0deg at the end. It's pretty sweet.

Here's a demo on JSBin:

http://jsbin.com/ogiqad/4/edit

(The code below uses -webkit but you can add all the other browser variations to make it work on more browsers.)

@-webkit-keyframes tilt-and-move {
  0% {
    left: 0;
    top: 0;
  }
  50% {
    -webkit-transform: rotate(8deg);
  }
  100% {
    left: 100px;
    top: 100px;
  }
}

#card {
    position: relative;
}

#card.moved {
    left: 100px;
    top: 100px;
    -webkit-animation-duration: 0.4s;
    -webkit-animation-name: tilt-and-move;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM