Thuộc tính animation-name
animation-name liên kết một phần tử với một @keyframes rule đã định nghĩa. Tên phải trùng khớp chính xác (phân biệt hoa/thường).
Cú pháp
animation-name: ten-keyframes | none;
/* Có thể nhiều animation: */
animation-name: slideIn, fadeIn, rotate; /* Chạy đồng thời */
Ví dụ cơ bản
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 200px;
position: relative;
background: red;
animation-name: myanim; /* Liên kết với @keyframes myanim */
animation-duration: 2s; /* Bắt buộc: thời lượng */
}
@keyframes myanim {
from { left: 0px; background-color: green; }
to { left: 100px; background-color: blue; }
}
</style>
</head>
<body>
<div></div>
</body>
</html>
Quy tắc đặt tên
- Không chứa space, ký tự đặc biệt (trừ `-`, `_`).
- Phân biệt chữ hoa/thường: `myAnim` ≠ `myanim`.
- Tránh trùng từ khóa CSS: `none`, `inherit`, `initial`, `unset`, `revert`.
- Đặt tên có ý nghĩa: `slide-in`, `fade-out`, `pulse`, `spin`.
Nhiều animation cùng lúc
.element {
animation-name: slideIn, fadeIn;
animation-duration: 0.5s, 1s;
animation-timing-function: ease-out, linear;
animation-delay: 0s, 0.2s;
animation-iteration-count: 1, infinite;
animation-fill-mode: forwards, none;
}
Animation shorthand
/* Thứ tự: name | duration | timing | delay | iteration | direction | fill-mode | play-state */
animation: myanim 2s ease-in 0s 3 alternate forwards running;
/* Nhiều animation */
animation:
slideIn 0.5s ease-out,
fadeIn 1s linear 0.2s infinite;
Lỗi thường gặp
- Quên
animation-duration(mặc định 0s → không chạy). - Sai tên keyframes (case-sensitive).
- Đặt `animation-name: none` vô hiệu hóa animation.