CSS3 design animation style

CSS3 animations include transition animations and keyframe animations, which are mainly simulated by changing CSS property values. I will introduce the three functional modules of Transform, Transitions and Animations in detail. Transform implements the deformation operation of web page objects, Transitions implements CSS attribute transition changes, and Animations implements the step-by-step demonstration effect of CSS styles.

1. CSS3 transformation

In September 2012, W3C released the CSS3 transformation working draft. This draft includes CSS3 2D transformations and CSS3 3D transformations. CSS 2D Transform is supported by all major browsers, but CSS 3D Transform support is not very complete. This section focuses on 2D deformation. For 3D deformation, you can refer to my other posts.

1.1. Setting the origin

The origin of CSS deformation defaults to the center point of the object (50% 50%). Use the transform-origin attribute to reset the new deformation origin. The syntax format is as follows:

 transform-origin: [ <percentage> | <length> | left | center① | right ] [ <percentage> | <length> | top | center② | bottom ]?

The value is simply explained as follows:

  • : Specify the coordinate value in percentage, which can be negative.
  • : Use the length value to specify the coordinate value, which can be a negative value.
  • left: Specify the abscissa coordinate of the origin as left.
  • center①: Specify the abscissa coordinate of the origin as center.
  • right: Specify the abscissa of the origin as right.
  • top: Specify the ordinate of the origin as top.
  • center②: Specify the ordinate of the origin as center.
  • bottom: Specify the ordinate of the origin as bottom.

[Example] By resetting the deformation origin, you can design different deformation effects. Rotate the image 45 degrees counterclockwise with the upper right corner of the image as the origin:

 <style type="text/css">
    img {<!-- --> /* Fix the two images to be the same size and display position */
        position: absolute;
        left: 20px;
        top: 10px;
        width: 170px;
        width: 250px;
    }
    img.bg {<!-- --> /* Set the first image as a reference */
        opacity: 0.3;
        border: dashed 1px red;
    }
    img.change {<!-- --> /* Transform the second image */
        border: solid 1px red;
        transform-origin: top right; /* Transform with the upper right corner as the origin*/
        transform: rotate(-45deg); /* Rotate 45 degrees counterclockwise*/
    }
    </style>
    <img class="bg" src="images/1.jpg">
    <img class="change" src="images/1.jpg">

The comparison effect is shown in the figure below:

1.2, 2D rotation

The rotate() function can rotate objects in 2D space. The syntax format is as follows:

 rotate(<angle>)

Among them, the parameter angle represents the angle value, and the value unit can be: degree, such as 90deg (90 degrees, 360 degrees in a circle); gradient, such as 100 grad (equivalent to 90 degrees, 360 degrees is equal to 400 grad); radians, such as 1.57 rad (approximately equal to 90 degrees, 360 degrees is equal to 2π); circle, such as 0.25 turn (equal to 90 degrees, 360 degrees is equal to 1 turn).

[Example] Based on the example in the previous section, rotate the image 45 degrees counterclockwise according to the default origin:

 img.change {<!-- -->
        border: solid 1px red;
        transform: rotate(-45deg);
    }

Results as shown below:

1.3, 2D scaling

The scale() function can scale the object size. The syntax format is as follows:

 scale(<number>[, <number>])

This function contains two parameter values, which are used to define the scaling ratio of width and height. The value is simply explained as follows:

  • If the value is positive, the object will be enlarged or reduced based on the specified width and height.
  • If the value is negative, the element will not be reduced, but will be flipped (such as text being reversed) and then scaled.
  • If the value is a decimal less than 1 (such as 0.5), the element can be reduced.
  • If the second parameter is omitted, the second parameter is equal to the value of the first parameter.

[Example] Continuing based on the example in the previous section, reduce the image by 1/2 according to the default origin:

 img.change {<!-- -->
        border: solid 1px red;
        transform: scale(0.5);
    }

1.4, 2D translation

The translate() function can translate the position of the object. The syntax format is as follows:

 translate(<translation-value>[, <translation-value>])

This function contains two parameter values, which are used to define the offset distance of the object on the x-axis and y-axis relative to the origin. If the argument is omitted, the default value is 0. A negative value represents a reverse offset and the reference origin remains unchanged.

[Example] Design to translate the image toward the lower right corner, with an x-axis offset of 150px and a y-axis offset of 50px:

 img.change {<!-- -->
        border: solid 1px red;
        transform: translate(150px, 50px);
    }

1.5, 2D tilt

The skew() function can tilt the display object. The syntax format is as follows:

 skew(<angle> [, <angle>])

This function contains two parameter values, which are used to define the tilt angle of the object on the x-axis and y-axis. If the argument is omitted, the default value is 0. Unlike the rotate() function, the rotate() function only rotates the angle of the object without changing the shape of the object; the skew() function changes the shape of the object.

[Example] Use the skew() function to deform the image, with the x-axis tilted by 30 degrees and the y-axis tilted by 20 degrees:

 img.change {<!-- -->
        border: solid 1px red;
        transform: skew(30deg, 20deg);
    }

Results as shown below:

1.6, 2D matrix

matrix() is a matrix function that can simultaneously implement scaling, rotation, translation and tilt operations. The syntax format is as follows:

 matrix(<number>, <number>, <number>, <number>, <number>, <number>)

This function contains 6 values, the details are as follows:

  • The first parameter controls the x-axis scaling.
  • The second parameter controls the x-axis tilt.
  • The 3rd parameter controls the y-axis tilt.
  • The 4th parameter controls the y-axis scaling.
  • The fifth parameter controls the x-axis translation.
  • The sixth parameter controls the y-axis translation.

[Example] Use matrix() function to simulate:

 img.change {<!-- -->
        border: solid 1px red;
        transform: matrix(1, 0.6, 0.2, 1, 0, 0);
    }

Tip: Multiple transformation functions can be defined simultaneously in one declaration. For example:

 div {<!-- -->
        transform: translate(80, 80);
        transform: rotate(45deg);
        transform: scale(1.5, 1.5);}

For the above style, it can be simplified to:

 div {<!-- --> transform: translate(80, 80) rotate(45deg) scale(1.5, 1.5);}

2. Transition animation

In February 2013, W3C released a working draft of CSS Transitions. This draft describes the basic implementation methods and properties of CSS transition animations and is currently supported by all browsers.

2.1. Set transition attributes

The transition-property attribute defines the CSS property name of the transition animation. The basic syntax is as follows:

 transition-property:none | all | [ <IDENT> ] [ ,’ <IDENT> ]*;

The value is simply explained as follows:

  • none: Indicates no element.
  • all: Default value, indicating that it is for all elements, including :before and :after pseudo-elements.
  • IDENT: Specify a list of CSS properties. Almost all CSS properties related to color, size or position, including many newly added CSS3 properties, can apply transitions, such as enlargement, reduction, rotation, bevel, gradient, etc. in CSS3 transformations.

[Example] Specify the animation attribute as the background color. In this way, when the mouse passes over the box, it will automatically transition from the red background to the blue background:

 <style type="text/css">
    div {<!-- -->
        margin: 10px auto; height: 80px;
        background: red;
        border-radius: 12px;
        box-shadow: 2px 2px 2px #999;
    }
    div:hover {<!-- -->
        background-color: blue;
        /*Specify the CSS properties of animation transition*/
        transition-property: background-color;
    }
    </style>
    <div></div>

2.2. Set transition time

The transition-duration attribute defines the duration of the transition animation. The basic syntax is as follows:

 transition-duration:<time> [, <time>]*;

Among them, the initial value is 0, which applies to all elements, as well as the :before and :after pseudo-elements. By default, the animation transition time is 0 s. When specifying element animation, you will not see the transition process, but directly see the result.

[Example] Taking the example in the previous section as an example, set the animation transition time to 2 s. When the mouse moves over the object, you will see the background color gradually transition from red to blue:

 div:hover {<!-- -->
        background-color: blue;
        /*Specify the CSS properties of animation transition*/
        transition-property: background-color;
        /*Specify the time of animation transition*/
        transition-duration:2s;
    }

2.3. Set delay transition time

The transition-delay attribute defines the delay time for starting the transition animation. The basic syntax is as follows:

 transition-delay:<time> [, <time>]*;

Among them, the initial value is 0, which applies to all elements, as well as the :before and :after pseudo-elements. The set time can be a positive integer, a negative integer, or zero. When it is non-zero, the unit must be set to s (seconds) or ms (milliseconds); when it is a negative number, the transition action will be displayed from that time point, and the previous action will be truncated; when it is a positive number, the transition action will Delay trigger.

[Example] Continuing to introduce based on the example in the previous section, set the transition animation to be delayed for 2 seconds. Then when the mouse moves over the object, you will not see any change. After 2 seconds, you will find that the background color gradually transitions from red to blue.

 div:hover {<!-- -->
        background-color: blue;
        /*Specify the CSS properties of animation transition*/
        transition-property: background-color;
        /*Specify the time of animation transition*/
        transition-duration: 2s;
        /*Specify animation delay trigger */
        transition-delay: 2s;
    }

2.4. Set transition animation type

The transition-timing-function attribute defines the type of transition animation. The basic syntax is as follows:

 transition-timing-function:ease | linear | ease-in | ease-out | ease-in-out | cubicbezier(<number>, <number>, <number>, <number>)
[, ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>,<number>, <number>)]*

The initial value of the attribute is ease, and the value is briefly explained as follows:

  • Ease: Smooth transition, equivalent to the cubic-bezier(0.25, 0.1, 0.25, 1.0) function, that is, cubic Bezier.
  • linear: linear transition, equivalent to the cubic-bezier(0.0, 0.0, 1.0, 1.0) function.
  • ease-in: from slow to fast, equivalent to the cubic-bezier(0.42, 0, 1.0, 1.0) function.
  • ease-out: from fast to slow, equivalent to the cubic-bezier(0, 0, 0.58, 1.0) function.
  • ease-in-out: from slow to fast to slow, equivalent to the cubic-bezier(0.42,0, 0.58, 1.0) function.
  • cubic-bezier: special cubic Bezier curve effect.

[Example] Continuing the introduction based on the example in the previous section, set the transition type to linear effect. The code is as follows:

 div:hover {<!-- -->
        background-color: blue;
        /*Specify the CSS properties of animation transition*/
        transition-property: background-color;
        /*Specify the time of animation transition*/
        transition-duration: 10s;
        /*Specify the animation transition as a linear effect */
        transition-timing-function: linear;
    }

2.5. Set transition trigger action

CSS3 transition animations are generally triggered through dynamic pseudo-classes, as shown in the following table:

It can also be triggered by JavaScript events, including click, focus, mousemove, mouseover, mouseout, etc.

1.:hover

The most commonly used transition triggering method is to use the :hover pseudo-class.

[Example 1] Design: When the mouse passes over a div element, the background color of the element will dynamically change from green to blue within 2 s after an initial delay of 1 s.

 <style type="text/css">
    div {<!-- -->
        margin: 10px auto;
        height: 80px;
        border-radius: 12px;
        box-shadow: 2px 2px 2px #999;
        background-color: red;
        transition: background-color 2s ease-in 1s;
    }
    div:hover {<!-- --> background-color: blue}
    </style>
    <div></div>

2.:active

The :active pseudo-class represents the state displayed when the user clicks an element and holds down the mouse button.

[Example 2] Design: When the user clicks on the div element, the element is activated, and the animation is triggered. The height attribute transitions from 200px to 400px. If you press and hold the element and keep it active, the div element will always display a height of 400px. After releasing the mouse, it will return to its original height:

 <style type="text/css">
    div {<!-- -->
        margin: 10px auto;
        border-radius: 12px;
        box-shadow: 2px 2px 2px #999;
        background-color: #8AF435;
        height: 200px;
        transition: width 2s ease-in;
    }
    div:active {<!-- -->height: 400px;}
    </style>
    <div></div>

3.: focus

The :focus pseudo-class usually appears when a form object receives a keyboard response.

[Example 3] When the input box gets focus, the background color of the input box is gradually highlighted, as shown in the following figure:

 <style type="text/css">
    label {<!-- -->
        display: block;
        margin: 6px 2px;
    }
    input[type="text"], input[type="password"] {<!-- -->
        padding: 4px;
        border: solid 1px #ddd;
        transition: background-color 1s ease-in;
    }
    input:focus {<!-- --> background-color: #9FFC54;}
    </style>
    <form id=fm-form action="" method=post>
        <fieldset>
            <legend>User login</legend>
            <label for="name">Name
                <input type="text" id="name" name="name" >
            </label>
            <label for="pass">Password
                <input type="password" id="pass" name="pass" >
            </label>
        </fieldset>
    </form>


Tip: Using the :hover pseudo-class with :focus can enrich the experience of mouse users and keyboard users.

4.:checked

The :checked pseudo-class triggers a transition when a check occurs, and returns to the original state when unchecked.

[Example 4] Design to slowly indent 2 characters when the check box is selected:

 <style type="text/css">
    label.name {<!-- -->
        display: block;
        margin: 6px 2px;
    }
    input[type="text"], input[type="password"] {<!-- -->
        padding: 4px;
        border: solid 1px #ddd;
    }
    input[type="checkbox"] {<!-- --> transition: margin 1s ease;}
    input[type="checkbox"]:checked {<!-- --> margin-left: 2em;}
    </style>
    <form id=fm-form action="" method=post>
        <fieldset>
            <legend>User login</legend>
            <label class="name" for="name">Name
                <input type="text" id="name" name="name" >
            </label>
            <p>technical expertise<br>
                <label>
                    <input type="checkbox" name="web" value="html" id="web_0">
                    HTML</label><br>
                <label>
                    <input type="checkbox" name="web" value="css" id="web_1">
                    CSS</label><br>
                <label>
                    <input type="checkbox" name="web" value="javascript" id="web_2">
                    JavaScript</label><br>
            </p>
        </fieldset>
    </form>

Demonstration effect:

5. Media inquiry

Another way to trigger an element’s state change is to use CSS3 media queries.

[Example 5] Design the width and height of the div element to be 49% × 200px. If the user resizes the window to 420px or less, the element will transition to 100% × 100px. That is to say, when the window width changes past the 420px threshold, the transition animation will be triggered:

 <style type="text/css">
    div {<!-- -->
        float: left; margin: 2px;
        width: 49%; height: 200px;
        background: #93FB40;
        border-radius: 12px;
        box-shadow: 2px 2px 2px #999;
        transition: width 1s ease, height 1s ease;
    }
    @media only screen and (max-width : 420px) {<!-- -->
        div {<!-- -->
            width: 100%;
            height: 100px;
        }
    }
    </style>
    <div></div>
    <div></div>

6. JavaScript events

[Example 6] You can use pure CSS pseudo-classes to trigger the transition. In order to facilitate user understanding, the transition is triggered through a jQuery script:

 <script type="text/javascript" src="images/jquery-1.10.2.js"></script>
    <script type="text/javascript">
    $(function() {<!-- -->
        $("#button").click(function() {<!-- -->
            $(".box").toggleClass("change");
        });
    });
    </script>
    <style type="text/css">
    .box {<!-- -->
        margin:4px;
        background: #93FB40;
        border-radius: 12px;
        box-shadow: 2px 2px 2px #999;
        width: 50%; height: 100px;
        transition: width 2s ease, height 2s ease;
    }
    .change {<!-- --> width: 100%; height: 120px;}
    </style>
    <input type="button" id="button" value="Trigger transition animation" />
    <div class="box"></div>

Contain a box of box class and a button in the document. When the button is clicked, the jQuery script will switch the box’s class to change, thus triggering the transition animation:

The above demonstrates that changes to the style will result in transition animations, but these changes can also be triggered through other methods, including dynamic changes through JavaScript scripts. From the perspective of execution efficiency, events should usually be triggered through JavaScript, while simple animations or transitions should be triggered using CSS.

3. Frame animation

In April 2012, W3C released a working draft of CSS Animations, which describes the basic implementation methods and properties of CSS keyframe animation. Currently, all major browsers support CSS frame animation.

3.1. Set key frames

CSS3 uses @keyframes to define key frames. The specific usage is as follows:

 @keyframes animationname {<!-- -->
        keyframes-selector {<!-- -->
            css-styles;
        }
    }

The parameters are described as follows:

  • animationname: defines the name of the animation.
  • keyframes-selector: defines the time position of the frame, which is the percentage of animation duration. Legal values include: 0~100%, from (equivalent to 0), to (equivalent to 100%).
  • css-styles: Represents one or more legal CSS style attributes.

During the animation design process, users can change CSS styles multiple times, define the time when style changes occur as a percentage, or through the keywords from and to. For optimal browser support, you should always define 0 and 100% position frames when designing keyframe animations. Finally, define dynamic styles for each frame and bind the animation to the selector.

[Example] Demonstrate making a small square box move at a constant speed along the inner wall of the square box:

 <style>
    #wrap {<!-- --> /* Define the motion trajectory containing box*/
        position:relative; /* Define the positioning containing box to prevent the small box from running outside */
        border:solid 1px red;
        width:250px; height:250px;
    }
    #box {<!-- --> /* Define the style of the sports box*/
        position:absolute;
        left:0; top:0;
        width: 50px; height: 50px;
        background: #93FB40;
        border-radius: 8px;
        box-shadow: 2px 2px 2px #999;
        /*Define frame animation: the name is ball, the animation duration is 5s, the animation type is uniform gradient, and the animation plays infinitely*/
        animation: ball 5s linear infinite;
    }
    /*Define key frames: including 5 frames in total, at 0, 25%, 50%, 75%, and 100% of the total duration*/
    /*Set animation attributes to left and top in each frame, let their values gradient at a uniform speed, and generate motion animation*/
    @keyframes ball {<!-- -->
        0 {<!-- -->left:0;top:0;}
        25% {<!-- -->left:200px;top:0;}
        50% {<!-- -->left:200px;top:200px;}
        75% {<!-- -->left:0;top:200px;}
        100% {<!-- -->left:0;top:0;}
    }
    </style>
    <div id="wrap">
        <div id="box"></div>
    </div>

3.2. Set animation attributes

The Animations function is the same as the Transition function, and both achieve animation effects by changing the attribute values of elements. The difference between them is that when using the Transitions function, the animation effect can only be achieved by specifying the start value and end value of the attribute, and then making a smooth transition between the two attribute values, so more complex animation effects cannot be achieved; and The Animations function achieves more complex animation effects by defining multiple keyframes and defining the attribute values of elements in each keyframe.

1. Define animation name

Use the animation-name attribute to define the name of a CSS animation. The syntax is as follows:

 animation-name:none | IDENT [, none | IDENT ]*;

Among them, the initial value is none, defining an applicable animation list. Each name is used to select an animation keyframe and provide a property value for the animation. If the name is none, there will be no animation.

2. Define animation time

Use the animation-duration attribute to define the playback time of CSS animations. The syntax is as follows.

 animation-duration:<time> [, <time>]*;

By default, this property value is 0, which means the animation period is 0, that is, there will be no animation. When the value is negative, it is treated as 0.

3. Define animation type

CSS animation types can be defined using the animation-timing-function attribute. The syntax is as follows.

 animation-timing-function:ease | linear | ease-in | ease-out | ease-in-out | cubicbezier(<number>, <number>, number>, <number>) [,
ease | linear |ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>,<number>, <number>)]*

The initial value is ease, and the value description can refer to the transition animation type introduced above.

4. Define delay time

Use the animation-delay attribute to define the delay time for CSS animations. The syntax is as follows:

 animation-delay:<time> [, <time>]*;

This property allows an animation to start executing some time before it is applied. When the animation delay time is 0, which is the default animation delay time, it means that the animation will be executed as soon as possible, otherwise the value specifies how long the execution will be delayed.

5. Define the number of plays

Use the animation-delay attribute to define the delay time for CSS animations. The syntax is as follows:

 animation-delay:<time> [, <time>]*;

This property allows an animation to start executing some time before it is applied. When the animation delay time is 0, which is the default animation delay time, it means that the animation will be executed as soon as possible, otherwise the value specifies how long the execution will be delayed.

6. Define playback direction

Use the animation-direction attribute to define the playback direction of CSS animations. The basic syntax is as follows.

 animation-direction:normal | alternate [, normal | alternate]*;

The default value is normal. When set to the default value, each iteration of the animation plays forward. The other value is alternate. Setting this value means playing forward for the even-numbered times and playing in the reverse direction for the odd-numbered times.

7. Define playback status

Use the animation-play-state attribute to define whether the animation is running or paused. The syntax is as follows:

 animation-play-state: paused|running;

The initial value is running. Among them, paused defines that the animation has been paused, and running defines that the animation is playing.

Tip: You can use this property in JavaScript to pause the animation during playback. The usage in JavaScript script is as follows.

8. Define the status outside playback

Use the animation-fill-mode attribute to define the state outside animation playback. The syntax is as follows.

 animation-fill-mode: none | forwards | backwards | both [ , none | forwards | backwards | both ]*

The initial value is none. If multiple attribute values are provided, separate them with commas. The value description is as follows:

  • none: Do not set the state other than object animation.
  • forwards: Set the object state to the state at the end of the animation.
  • backwards: Set the object state to the state when the animation starts.
  • both: Set the object state to the end or start state of the animation.

[Example] Design a small ball and define it to move horizontally to the left. After the animation ends, it will return to the starting point:

 <style>
    /*Start the moving ball and define the return after the animation ends*/
    .ball{<!-- -->
        width: 50px; height: 50px;
        background: #93FB40;
        border-radius: 100%;
        box-shadow:2px 2px 2px #999;
        animation:ball 1s ease backwards;
    }
    /*Define key frames for horizontal movement of the ball*/
    @keyframes ball{<!-- -->
        0%{<!-- -->transform:translate(0,0);}
        100%{<!-- -->transform:translate(400px);}
    }
    </style>
    <div class="ball"></div>

Results as shown below: