Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo hiệu ứng Swing (dao động như con lắc) với CSS

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ểmSwingWobble
Trục xoayTop center (cạnh trên)Center center (tâm)
Chuyển độngXoay quanh điểm cố địnhDịch chuyển ngang + xoay
Cảm giácCon lắc, cây cối gió thổiRung lắc, không ổn định
Phù hợpIcon treo, notification bell, menu dropdownButton 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 center cả 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 infinite cho hiệu ứng idle
  • Tránh dùng trên element lớn (layout shift) — thích hợp cho icon, button nhỏ