Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Swing Animation Effect with CSS
The swing animation effect creates a pendulum-like motion that moves an element back and forth or from side to side while rotating around a fixed pivot point. This animation simulates the natural swinging motion of an object suspended from above.
Syntax
@keyframes swing {
keyframe% { transform: rotate(angle); }
}
.element {
animation: swing duration timing-function iteration-count;
transform-origin: top center;
}
Example
The following example demonstrates a swing animation applied to a colored box that rotates back and forth like a pendulum −
<!DOCTYPE html>
<html>
<head>
<style>
.swing-container {
display: flex;
justify-content: center;
margin: 50px 0;
}
.swing-box {
width: 100px;
height: 100px;
background-color: #e74c3c;
border-radius: 10px;
animation: swing 2s ease-in-out infinite;
transform-origin: top center;
}
@keyframes swing {
20% { transform: rotate(15deg); }
40% { transform: rotate(-10deg); }
60% { transform: rotate(5deg); }
80% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
.trigger-btn {
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 20px;
}
</style>
</head>
<body>
<div class="swing-container">
<div class="swing-box"></div>
</div>
<center>
<button class="trigger-btn" onclick="location.reload()">Restart Animation</button>
</center>
</body>
</html>
A red square box appears on the page and continuously swings back and forth like a pendulum, rotating from 15 degrees to -10 degrees to 5 degrees to -5 degrees and back to 0 degrees in a smooth motion. A blue "Restart Animation" button appears below.
Key Properties
| Property | Value | Description |
|---|---|---|
transform-origin |
top center |
Sets the pivot point for rotation at the top center |
transform |
rotate(angle) |
Rotates the element by specified degrees |
animation-duration |
2s |
Controls the speed of the swing motion |
Conclusion
The swing animation effect creates realistic pendulum motion using CSS keyframes and the rotate transform. The transform-origin: top center property is crucial for achieving the proper pivot point for natural swinging motion.
Advertisements
