Home > Article > Web Front-end > How to use CSS to achieve the rotating background animation effect of elements
How to use CSS to achieve the rotating background animation effect of elements
The background animation effect can increase the visual appeal and user experience of the web page. This article will introduce how to use CSS to achieve the rotating background animation effect of elements, and provide specific code examples.
First, we need to prepare a background image, which can be any picture you like, such as a picture of the sun or an electric fan. Save the image and name it "bg.png".
Next, create an HTML file, add a div element to the file, and set it as the element where you need to add a background image. For example:
<!DOCTYPE html> <html> <head> <title>旋转背景图动画</title> <style> .element { width: 300px; height: 300px; background-image: url("bg.png"); background-size: cover; animation: rotate 5s infinite linear; } @keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> </head> <body> <div class="element"></div> </body> </html>
In the above code, we first define a CSS class named "element" and apply it to the div element where a background image needs to be added. The width and height of the div element are set to 300 pixels. The background image uses the previously prepared "bg.png", and the background image is scaled proportionally and covers the entire div element through the background-size attribute.
Next, we use the animation attribute to add a rotation animation called "rotate" to the div element. The animation will play in an infinite loop for 5 seconds, with a linear speed.
In the @keyframes rule, we define the keyframes of the animation. In the 0% keyframe, set the rotation angle of the picture to 0 degrees; in the 100% keyframe, set the rotation angle of the picture to 360 degrees to achieve the effect of a full rotation.
Finally, we added a div element within the body tag and applied the previously defined CSS class "element" to that element.
Save and run the HTML file, you will see the background image in the div element begin to rotate. This is how you use CSS to animate the rotating background of an element.
Summary:
By defining a rotation animation and using the background-image attribute, we can achieve the rotating background image animation effect of the element. We can achieve different effects by adjusting attributes such as animation time, rotation direction, and speed. The code examples provided above can help you get started creating your own rotating background animation. Hope this article can be helpful to you!
The above is the detailed content of How to use CSS to achieve the rotating background animation effect of elements. For more information, please follow other related articles on the PHP Chinese website!