Home > Web Front-end > CSS Tutorial > CSS Animation Guide: Teach you step-by-step to create shaking effects

CSS Animation Guide: Teach you step-by-step to create shaking effects

王林
Release: 2023-10-18 11:27:19
Original
1666 people have browsed it

CSS Animation Guide: Teach you step-by-step to create shaking effects

CSS Animation Guide: Teach you step-by-step to create shaking effects

In web design, animation effects can add a lively and interactive feel to the page. CSS animation is a technology that achieves animation effects by applying CSS rules on web pages. One of the common animation effects is the Shake effect, which can add a shaking animation effect to elements and add vitality to the web page. This article will take you from scratch, teach you step by step how to create a shaking effect, and provide specific code examples.

Step One: Create HTML Structure
First, we need to create an element assumed to be "shake" in the HTML file. You can wrap it with a

tag and add a unique ID attribute to it, such as "shake-element". The following is a sample code:
<div id="shake-element">
  这里是要添加抖动特效的内容
</div>
Copy after login

Step 2: Define CSS styles
Next, we need to define CSS styles to add jitter effects to elements. We'll define a starting position for the element and then create a jitter effect by applying a keyframe animation effect. The following is the code for an example CSS style:

#shake-element {
  position: relative;
  animation: shake-animation 1s infinite;
}

@keyframes shake-animation {
  0% { transform: translateX(0); }
  10% { transform: translateX(-10px); }
  20% { transform: translateX(10px); }
  30% { transform: translateX(-10px); }
  40% { transform: translateX(10px); }
  50% { transform: translateX(-10px); }
  60% { transform: translateX(10px); }
  70% { transform: translateX(-10px); }
  80% { transform: translateX(10px); }
  90% { transform: translateX(-10px); }
  100% { transform: translateX(0); }
}
Copy after login

In this CSS code, we first set position: relative for the element to ensure that it jitters relative to its original position. Then, define the specific effect of the jitter animation through keyframe animation@keyframes. In keyframe animation, each percentage defines a different position of the element, and the horizontal translation of the element is controlled through the transform: translateX() attribute. In the example, we use 10% of the time to control the jitter position of the element.

Step Three: Apply CSS Style
The last step is to apply the defined CSS style to the HTML element, that is, select and reference the CSS style through the ID attribute of the tag. In the tag in an HTML file, we can use the