CSS animation loop back and forth
CSS Animation Looping Back and Forward
In web design and development, animation effects are a very important part, which can attract users’ attention and enhance user experience. CSS animation is a method for creating animation effects without JavaScript. Looping animations are often used in advertisements, product presentations, and other scenarios. This article will detail how to create a simple looping effect using CSS animations.
CSS Animation Principles
In CSS, you can create an animation sequence using the @keyframes keyword. The @keyframes rule contains at least one percentage value, each corresponding to a state within the animation’s duration.
After defining the @keyframes
rule, you can apply it to an element using the animation
attribute. The animation
attribute must specify at least the animation name, duration, and motion curve.
Implementing a Looping Animation
Below, we’ll detail how to use CSS animations to create a looping animation effect.
HTML Structure
First, we need to define an element in HTML to display the animation effect. In this example, we use a <div>
element as the container.
<div class="box"></div>
CSS Style
Next, we use CSS to style this <div>
element and define the animation effect.
.box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: move 2s infinite;
}
@keyframes move {
0% {
transform: translateX(0);
}
50% {
transform: translateX(200px);
}
100% {
transform: translateX(0);
}
}
In the above code, we define a .box
class, set its width, height, and background color, and add an animation called move
to it. This animation defines the element’s X-axis displacement at 0%, 50%, and 100%, respectively, creating a back-and-forth motion effect. The infinite
keyword indicates that the animation will loop indefinitely.
Operational Effect
Add the above HTML and CSS code to an HTML file and open it in a browser. You should see a square that loops back and forth.
Summary
Through this article, we learned how to use CSS animation to create a simple looping back-and-forth motion effect. CSS animation can help us easily add various dynamic effects to web pages and enhance user experience.