CSS Transition คืออะไร?
ทำให้การเปลี่ยนแปลงค่า CSS Property เกิดขึ้น **อย่างนุ่มนวล (Smooth)** ภายในระยะเวลาที่กำหนด แทนที่จะเปลี่ยนทันที
องค์ประกอบ 2 ส่วน
- CSS Property ที่ต้องการให้ Transition (เช่น
background-color,width) - Duration (ระยะเวลา) - ค่าเริ่มต้น 0s = ไม่มี Transition
ตัวอย่าง: ปุ่มเปลี่ยนสีพื้นหลังเมื่อ Hover
div {
width: 100px; height: 100px;
border: 3px solid #33CCFF;
transition: background-color 2s; /* Property + Duration */
}
div:hover {
background-color: #33CCFF;
}
Hover → สีพื้นหลังเปลี่ยนจากสีขาวเป็นสีน้ำเงินภายใน 2 วินาที
Unhover → กลับสู่สีขาวภายใน 2 วินาที
Transition Timing Function (Speed Curve)
| Value | ลักษณะ |
|---|---|
ease | ช้า-เร็ว-ช้า (Default) |
linear | ความเร็วคงที่ |
ease-in | เริ่มช้า แล้วเร็วขึ้น |
ease-out | เริ่มเร็ว แล้วช้าลง |
cubic-bezier(n,n,n,n) | กำหนดเอง |
transition: background-color 2s linear;
Transition Delay
transition: background-color 2s ease 1s; /* Delay 1 วินาที */
Multiple Transitions
div {
transition: background-color 2s, border 2s;
}
div:hover {
background-color: #33CCFF;
border-color: pink;
}
Longhand vs Shorthand
Longhand (4 Properties)
transition-property: background-color; transition-duration: 2s; transition-timing-function: ease; transition-delay: 0.5s;
Shorthand (1 Line)
transition: background-color 2s ease 0.5s; /* property duration timing-function delay */
สรุป
CSS Transition สร้าง UX ที่นุ่มนวลด้วยโค้ดน้อย ใช้ Shorthand เขียนได้ 1 บรรทัด ควบคุม Property, Duration, Timing, Delay ได้ครบ