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

Thêm hiệu ứng chuyển động (Transition) khi hover với CSS

Transition tạo chuyển động mượt giữa 2 trạng thái (ví dụ: bình thường ↔ hover). Cú pháp: transition: property duration timing-function delay;

Ví dụ mã nguồn

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
  body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
  .scaleBtn {
    display: inline-block;
    background-color: #0c1377;
    border: none;
    color: white;
    padding: 16px 32px;
    text-align: center;
    font-size: 16px;
    transition: transform 0.3s ease, background-color 0.3s ease, box-shadow 0.3s ease;
    margin: 20px;
    border-radius: 8px;
    cursor: pointer;
  }
  .scaleBtn:hover {
    transform: scale(1.1);
    background-color: #1a23a0;
    box-shadow: 0 8px 20px rgba(12, 19, 119, 0.4);
  }
  .scaleBtn:active { transform: scale(0.98); } /* Feedback khi click */
</style>
</head>
<body>
<h1>Transition on hover example</h1>
<button class="scaleBtn">Di chuột qua đây</button>
</body>
</html>

Các thành phần Transition

Thành phầnGiá trị ví dụMô tả
propertytransform, background-color, allThuộc tính áp dụng transition. 'all' = tất cả thuộc tính thay đổi
duration0.3s, 300msThời gian chuyển động
timing-functionease, linear, ease-in, ease-out, ease-in-out, cubic-bezier(...)Đường cong tốc độ
delay0s, 0.2sĐộ trễ trước khi bắt đầu

Timing Functions phổ biến

  • ease (mặc định): Chậm - Nhanh - Chậm
  • linear: Tốc độ đều
  • ease-out: Nhanh đầu, chậm cuối (tốt cho UI response)
  • ease-in-out: Chậm đầu, nhanh giữa, chậm cuối
  • cubic-bezier(0.25, 0.46, 0.45, 0.94): Custom (dùng cubic-bezier.com)

Thuộc tính nên animate (GPU accelerated)

  • transform (translate, scale, rotate, skew)
  • opacity
  • filter (blur, brightness...)

Tránh animate: width, height, top, left, margin, padding, border-width (trigger layout/repaint, chậm).

Shorthand nhiều transition


.btn {
  transition:
    transform 0.2s ease-out,
    background-color 0.3s ease 0.1s, /* Delay 0.1s */
    box-shadow 0.3s ease;
}