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

CSS Transition Shorthand Property (Thuộc tính tóm tắt)

Thuộc tính transition shorthand gộp 4 thuộc tính con: property, duration, timing-function, delay.

Ví dụ mã nguồn

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

Cú pháp Shorthand


/* transition: property duration timing-function delay */
/* Mỗi property cách nhau bởi dấu phẩy */
transition: width 1s ease, height 2s ease-in 0.5s;

/* Tương đương */
transition-property: width, height;
transition-duration: 1s, 2s;
transition-timing-function: ease, ease-in;
transition-delay: 0s, 0.5s;

Thứ tự giá trị (Quan trọng)

Trình duyệt phân tích theo thứ tự: property → duration → timing-function → delay

  • 2 giá trị thời gian đầu tiên: duration rồi delay
  • Nếu chỉ 1 thời gian: là duration
  • transition: 1s = transition: all 1s ease 0s
  • transition: 1s 2s = transition: all 1s ease 2s (duration 1s, delay 2s)

Ví dụ thực tế: Button Hover States


.btn {
  padding: 12px 24px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  /* Transition mượt cho nhiều property */
  transition: 
    background-color 0.15s ease-out,
    transform 0.1s ease-out,
    box-shadow 0.15s ease-out,
    opacity 0.15s ease-out;
}
.btn:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,123,255,0.4);
}
.btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0,123,255,0.3);
  transition-duration: 0.05s; /* Nhanh hơn khi click */
}
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

Transition trên Pseudo-classes & Media Queries

  • :hover, :focus, :active, :checked, :target
  • @media (prefers-reduced-motion: reduce) { * { transition: none !important; } } - Respect accessibility
  • Class toggle qua JS: element.classList.add('open') trigger transition

Lưu ý

  • Không thể transition display, visibility (discrete) - dùng opacity + pointer-events
  • auto height/width không transition được - dùng max-height hack hoặc Grid/Flex
  • Transition trên transform và opacity chạy trên compositor thread (smooth 60fps)