Giới thiệu
Hiệu ứng Swing làm phần tử dao động quanh trục ngang ở đỉnh (top center), giống như con lắc hoặc cái bánh răng. Khác với wobble (rung ngang), swing xoay quanh điểm cố định ở trên.
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top: 95px;
margin-bottom: 60px;
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes swing {
20%, 40%, 60%, 80%, 100% { -webkit-transform-origin: top center; }
20% { -webkit-transform: rotate(15deg); }
40% { -webkit-transform: rotate(-10deg); }
60% { -webkit-transform: rotate(5deg); }
80% { -webkit-transform: rotate(-5deg); }
100% { -webkit-transform: rotate(0deg); }
}
@keyframes swing {
20% { transform: rotate(15deg); }
40% { transform: rotate(-10deg); }
60% { transform: rotate(5deg); }
80% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
.swing {
-webkit-transform-origin: top center;
transform-origin: top center;
-webkit-animation-name: swing;
animation-name: swing;
}
</style>
</head>
<body>
<div id="animated-example" class="animated swing"></div>
<button onclick="myFunction()">Tải lại trang</button>
<script>
function myFunction() { location.reload(); }
</script>
</body>
</html>
Phân tích keyframes
Điểm neo (transform-origin: top center) cố định ở trung tâm cạnh trên. Góc xoay dao động giảm dần (damping):
- 20%: +15° (nghêng phải tối đa)
- 40%: -10° (nghêng trái)
- 60%: +5° (nghêng phải nhẹ)
- 80%: -5° (nghêng trái nhẹ)
- 100%: 0° (thẳng đứng)
So sánh Swing vs Wobble
| Đặc điểm | Swing | Wobble |
|---|---|---|
| Trục xoay | Top center (cạnh trên) | Center center (tâm) |
| Chuyển động | Xoay quanh điểm cố định | Dịch chuyển ngang + xoay |
| Cảm giác | Con lắc, cây cối gió thổi | Rung lắc, không ổn định |
| Phù hợp | Icon treo, notification bell, menu dropdown | Button error, badge, loading |
Biến thể: Swing liên tục (infinite)
@keyframes swing-infinite {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(10deg); }
75% { transform: rotate(-10deg); }
}
.swing-loop {
transform-origin: top center;
animation: swing-infinite 2s ease-in-out infinite;
}
Lưu ý
- Phải đặt
transform-origin: top centercả trên class và trong keyframes (đảm bảo nhất quán cross-browser) - Duration 1s là chuẩn; có thể dùng
2s ease-in-out infinitecho hiệu ứng idle - Tránh dùng trên element lớn (layout shift) — thích hợp cho icon, button nhỏ