10 minutes to get started CSS3 Animation

  animation, css3, Css3 animation, html

brief introduction

Animation allows you to easily realize various animation effects in web pages with pure CSS without relying on javascript or jquery.

Compatibility

Animation is well supported in most mainstream browsers! Students who are still compatible with IE9 should use them carefully.

image

CSS coordinate system

Before understanding animation, it is necessary to know the coordinate system of css, because many animation effects are closely related to the coordinates of elements. In css3, the webpage is no longer a two-dimensional plane, but a three-dimensional space. The horizontal direction, vertical direction and vertical screen direction respectively correspond to the X, Y and Z axes of the three-dimensional coordinate system, as shown in the following figure. The direction of the arrow is positive and vice versa (note that the Y-axis direction is opposite to the conventional Cartesian coordinate system).

image

Animations

1. Transforms

Transformation is translated into Chinese as “transformation”, but I prefer to call it “transformation” (the famous transformer is called transformer). We can use transform function to make html elements produce various deformations, such as translation, scaling, rotation, distortion, etc., without affecting the normal document flow.

(1) Translate

Translation is generally Translate as “translation”, but it is generally used as “translation” in css because translation is used to change the position of html elements in the 3d coordinate system. Translate supports moving in any direction within the coordinate system (by arbitrarily combining vectors in x, y and z directions), and the units can be length units and percentages (Percentages are relative to the size of the element itself being translated, the x axis is relative to width, and the y axis is relative to height. in the z axis direction, because the element has no’ thickness’, it cannot be expressed as percentages for the z direction), for example:

transform: translateX(100px) translateY(50%) translateZ(-100px);
//or shorthand
transform: translate3d(100px, 50%, 2em);

Note:

  1. translateIs a 2-dimensional translation in the xy plane,translate3dIs a three-dimensional translation in xyz space;
  2. translateCan also be written separately, such astranslate: 50% 105px 5rem;However, this feature is still in the experimental stage and is not supported by many browsers, so it is still suitable at this stage.transformUse. For details, please refer toMDN translate.

(2) Scale

Scale means “zoom”, as the name implies, is used to change the size of an element. For example:

transform: scaleX(2) scaleY(0.5) scaleZ(1);
//or shorthand
transform: scale3d(2, 0.5, 1);

scaleMethods any number (positive and negative integer, decimal, 0) is received as a parameter. the parameter is a scaling factor. the effect of coefficient > 1 is amplification, the effect of coefficient < 0 < 1 is reduction, the element size of coefficient =0 becomes infinitely small and invisible, and the effect of coefficient < 0 is mirror image of > 0 (the specific effect can be tested by oneself).

AndtranslateSimilarly,scaleThere are also 2 dimensionsscale()And three-dimensionalscale3d()Points, can also be written separately, not here.

(3) Rotate

Rotate means “rotate” and supports the rotation of elements with x, y and z as axes. the positive direction of rotation is the positive counterclockwise direction facing the coordinate axis. please refer to the schematic diagram of the coordinate system above.rotateThe method receives an angle as a parameter, the angle > 0 rotates in the positive direction and the angle < 0 rotates in the negative direction, for example:

//Rotate around Z axis by default
transform: rotate(90deg);

transform: rotateX(30deg) rotateY(60deg) rotateZ(-90deg);

Unlike translate and scale, rotate cannot be abbreviated astransform: rotate3d(30deg, 60deg, 90deg)In the form of,rotate3dThe usage of is: the first three parameters are numbers, representing vectors in x, y and z directions, adding to obtain vector v, and the fourth parameter is an angle, representing an angle rotating counterclockwise with vector v as its axis. the syntax is as follows:

transform: rotate3d(1, 2, 3, 90deg);

AndtranslateAndscaleSimilarly,rotateIt can also be used as a separate css attribute, but it is still in the experimental stage.

For space reasons, I will only list the three most commonly used tranform functions. please refer to the remaining tranform functions.MDN transform function.

(4) Combination

We can combine different transform methods, such as:

transform: translateY(200px) rotateZ(90deg) scale(3);

The order of execution of the combination method is from right to left, i.e. scale is executed first, then rotate and finally translate, and the results are accumulated one by one. Methods The order of writing has a great influence on the final effect. Look at the following example, translation and amplification along the Y axis. The results are obviously different depending on the order:

image

If translate and scale first, the translation distance will be scaled equally, but scale and translate first will not. Therefore, when using transform, you should followtranslate -> rotate -> scaleIn order to avoid enlarging the effect of translation, scale should be executed first, while rotate should be executed first to prevent rotation with translation distance. I think this is the inconvenient place for transform at present, because the mutual interference between methods is not easy to understand and the writing order is not easy to remember. In the future, it is expected to solve this problem by using independent css transform attributes, because independent transform attributes do not depend on writing order and methods will not interfere with each other.

Transition

Transition is translated as “transition” and emphasizes the process. In css, a dynamic process in which an element transitions from one state (corresponding to a css attribute) to another within a period of time. We can decide how to make the transition and how long it will take.

For example, when we hover the mouse over the cloud to make it larger, we can write this:

.cloud{
 width: 240px;
 transition: 1s;
 }
 .cloud:hover{
 width: 320px;
 }

Effect:

image

Transition can be used in combination with transform, for example, we can make one revolution while making the cloud bigger:

.cloud:hover{
width: 320px;
transform: rotate(360deg);
}

Effect:

image

We can set different transition times for different effects:

.cloud{
 width: 240px;
 transition: width 1s, transform 0.5s;
 }

We can also set a delay time for the effect, for example, we can wait for the width to increase before rotating:

.cloud{
 width: 240px;
 transition: width 1s, transform 0.5s 1s;
 }

Effect:

image

We can also set a different timing function for each effect to control the acceleration effect.

For example, we can speed up the rotation gradually:

.cloud{
 width: 240px;
 transition: transform 2s ease-in;
 }
 
 .cloud:hover{
 transform: rotate(1080deg);
 }

Effect:

image

More timing function will be discussed later and can also be consulted.MDN transition-timing-functions

Keyframes

(1) Basic usage

Keyframe, translated into Chinese as “keyframe”, is a very powerful function in animation. Generally speaking, we can create animation by defining key points and key states in an animation. Keyframes have stronger control over animation process and details than transition.

Let’s look at an example first (some codes are omitted)

html:

<div class="sky"></div>
<div class="grass"></div>
<div class="road">
<div class="lines"></div>
<img src="http://lc-jOYHMCEn.cn-n1.lcfile.com/a3f630c957a4b32d0221.png" class="mario animated">
</div>

css:

.mario{
 position: absolute;
 left: 0px;
 width: 100px;
 }
 
 .animated{
 animation-name: drive;
 animation-duration: 1s;
 animation-timing-function: linear;
 }
 
 @keyframes drive {
 from{ transform: translateX(0) }
 to{ transform: translateX(700px) }
 }

Effect:

image

among themdriveIs the name of the keyframes.from, toIs the beginning and end of the keyframes playback process, and the time point can also be expressed as a percentage, such as50%,from, toEquivalent to0%, 100%. Each time point corresponds to a css state, representing a keyframe. After the keyframes definition is completed, the usage method is as follows:

Animation also has short forms, such as:

animation: slidein 3s ease-in 1s infinite reverse both running;

However, this requires a certain order of writing (delay should be written after duration, other parameters have no order requirement, css will be identified by the keyword passed in).

(2) Animation Delay

viaanimation-delay, we can give animation delay execution:

animation-delay: 2s;

(3) Animation Fill Mode

forwards

In the above example, we can see that Mario has returned to the starting point after moving to the right. What if we want him to stay on the right after moving? It’s very simple. we can just set up ann imagination fillmode:

animation-fill-mode: forwards

forwardsIndicates that the element will remain in the last frame state after the animation is completed.

backwards

In contrast, there are alsobackwards,backwardsIndicates that the element does not change back to the state of the first frame after the animation is completed, but indicates that when it is setanimation-delayWhen, in the waiting process before the animation starts, the state of the first frame is applied to the element immediately. We will slightly modify the above example to see the effect:

.animated{
animation-name: drive;
animation-duration: 1s;
animation-fill-mode: backwords;
animation-delay: 1s;
animation-timing-function: linear;
}

@keyframes drive {
from{ transform: translateX(350px) }
to{ transform: translateX(700px) scale(2) }
}

Effect:

image

As you can see, the villain immediately moved to 350px before the animation started, and the animation started only 1s later.

both

Obviously, both will apply both forwards and backwards rules at the same time, i.e. the state of the first frame will be applied in delay and the state of the last frame will be maintained at the end.

(3) Animation Repeat

We can pass.animation-iteration-countSet the number of animation loops, for example:

animation-iteration-count: 3;
 
 //infinite loop
 animation-iteration-count:infinite;

Like this:

image

(4) Animation Direction

normal

The normal direction is also the default direction, that is, from before to.

reverse

Contrary to the normal direction, i.e. to first, then from. For example:

.animated{
...

animation-direction: reverse;
}

@keyframes drive {
from{ transform: translateX(-100px) rotateY(180deg) }
to{ transform: translateX(862px) rotateY(180deg)}
}

Effect:

image

alternate

Alternate means “alternate”, that is, the alternate journey between normal and reverse, normal before reverse.

reverse alternate

Reverse alternate, first reverse and then normal.

(4) Animation Timing function

Like transition, keyframes can also set a timing function. the commonly used timing function can be summarized as follows:

  1. Ease: default method, the initial speed is slow, then speed up and then slow down
  2. Ease-in: The initial speed is the slowest, and then it has been accelerating.
  3. Ease-out: the first speed is the fastest, and then it slows down all the time.
  4. Ease-in-out: the initial speed is slow, then accelerate and decelerate. the difference with ease is that the acceleration and deceleration process is symmetrical.
  5. Linear: Constant Speed Motion

Visual performance is as follows (codepen):

image

In addition to the above off-the-shelf methods, we can customize the speed curve through Bezier curves. We can do it athttp://cubic-bezier.comVisually create our own Bezier curves. For example, create a curve that starts very slowly and suddenly becomes extremely fast:

image

css:

animation-timing-function: cubic-bezier(1,.03,1,-0.03);

Effect:

image

Isn’t it amazing?

(5) Chain Animation

We can use multiple animation in series. For example, we want little people to jump while driving. We can write this:

css:

.mario {
...

animation: drive 3s both infinite linear, jump 0.5s 1.2s ease-in-out infinite;
}

@keyframes jump {
0% { top: -40px;  }
50% { top: -120px;  }
100% { top: -40px;  }
}

Effect:

image

Practice

The purpose of this article is to popularize the foundation of css3 animation, which does not completely cover the knowledge of animation. Please forgive me for the knowledge not involved and explained. After mastering the above knowledge, we can already use animation to make rich animation effects. Here are some small examples from codepen:

  1. full mario demo
  2. animated popup
  3. fly items to shopping cart
  4. flipping cards