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

Tạo hiệu ứng Transition (Chuyển động) với CSS3

CSS Transition tạo chuyển động mượt giữa 2 trạng thái CSS (hover, focus, active, class toggle, media query change...).

Ví dụ mã nguồn

<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
  .container {
    width: 300px; height: 100px;
    background: rgb(25, 0, 255);
    border: 2px solid red;
    transition: width 2s ease, background-color 2s ease, border-radius 2s ease;
  }
  .container:hover {
    width: 100px;
    background-color: purple;
    border-radius: 50%;
  }
</style>
</head>
<body>
<h1>Transition Effects Example</h1>
<div class="container"></div>
<h2>Di chuột qua div để xem co lại, đổi màu, bo tròn</h2>
</body>
</html>

Transition Properties

PropertyMô tảGiá trị
transition-propertyThuộc tính áp dụng transitionall | none | <property> (width, transform, opacity...)
transition-durationThời gian chuyển động<time> (s, ms) - mặc định 0s
transition-timing-functionĐường cong tốc độease | linear | ease-in | ease-out | ease-in-out | cubic-bezier() | steps()
transition-delayĐộ trễ trước khi bắt đầu<time> - mặc định 0s

Shorthand


/* transition: property duration timing-function delay */
transition: width 2s ease 0.5s;
transition: transform 0.3s, opacity 0.3s, background 0.3s; /* Nhiều property */
transition: all 0.3s ease; /* Tất cả property thay đổi */

Timing Functions chi tiết

  • ease: Chậm - Nhanh - Chậm (mặc định)
  • linear: Tốc độ đều
  • ease-in: Chậm đầu → Nhanh
  • ease-out: Nhanh → Chậm cuối (tốt cho UI response)
  • ease-in-out: Chậm - Nhanh - Chậm (cân bằng)
  • cubic-bezier(x1,y1,x2,y2): Tùy chỉnh (cubic-bezier.com)
  • steps(n, start|end): Nhảy theo bước (sprite animation)

Thuộc tính NÊN transition (GPU friendly)

  • transform (translate, scale, rotate, skew)
  • opacity
  • filter (blur, brightness...)
  • color, background-color, border-color (repaint only)

Thuộc tính KHÔNG NÊN transition (Layout thrashing)

  • width, height, top, left, margin, padding, border-width, font-size
  • Thay bằng: transform: scale(), transform: translate()

JavaScript Trigger


// Toggle class để trigger transition
element.classList.add('expanded');

// Force reflow trước khi add class (nếu element mới thêm vào DOM)
element.offsetHeight; // Trigger reflow
element.classList.add('animate');