CSS Transitions: ทำให้การเปลี่ยนแปลง Property นุ่มนวล
transition property กำหนด property ที่จะ transition, duration, timing function, delay ใช้กับ pseudo-classes (:hover, :focus) หรือ class toggle ด้วย JS
โค้ดตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
.container div {
width: 300px; height: 100px; background: rgb(25, 0, 255);
border: 2px solid red; transition: width 2s;
}
.container:hover div { width: 100px; }
</style>
</head>
<body>
<h1>Transition Effects Example</h1>
<div class="container"><div></div></div>
<h2>Hover บน div เหนือเพื่อลดความกว้าง</h2>
</body>
</html>
Transition Syntax (Shorthand)
transition: property duration timing-function delay;
/* ตัวอย่าง */
transition: width 2s ease-in-out 0.5s;
transition: background-color 0.3s, transform 0.2s ease-out;
transition: all 0.3s ease; /* ทุก property ที่เปลี่ยน */
Longhand Properties
transition-property– property ที่จะ transition (all/none/property list)transition-duration– ระยะเวลา (s, ms) default 0stransition-timing-function– easing (ease, linear, ease-in, ease-out, ease-in-out, cubic-bezier, steps)transition-delay– หน่วงก่อนเริ่ม (s, ms) default 0s
Animatable Properties (สำคัญ)
ไม่ใช่ทุก property transition ได้ – ต้องเป็น interpolatable (มีค่าระหว่าง): colors, lengths, percentages, angles, numbers, transform, opacity, shadow, filter, etc.
ไม่ได้: display, position, float, overflow, z-index, font-family, background-image (gradient), auto values
Performance
- ใช้
transformและopacityหลัก – GPU accelerated - หลีกเลี่ยง width/height/top/left/margin/padding – trigger layout
will-change: transform, opacityบอก browser เตรียม layer