ตัวอย่างพื้นฐานของการสร้างแอนิเมชันเปลี่ยนความสูง (height) ของ element ด้วย @keyframes
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid black;
width: 300px;
height: 100px;
animation: myanim 5s infinite;
}
@keyframes myanim {
30% {
height: 400px;
}
}
</style>
</head>
<body>
<div>This is demo text</div>
</body>
</html>
คำอธิบาย: กล่องเริ่มต้นสูง 100px ที่ 30% ของแอนิเมชัน 5 วินาที จะขยายสูงเป็น 400px แล้วหดกลับมาที่ 100px และวนซ้ำ
ข้อควรระวังด้านประสิทธิภาพ: การ animate height (และ width) ทำให้เกิด Layout Reflow ทุกเฟรม ซึ่งมีต้นทุนสูง (expensive) และอาจทำให้ animation ลื่นไหลไม่ได้บนอุปกริต่ำสุด
ทางเลือกที่ดีกว่า: ใช้ transform: scaleY() แทน ซึ่งทำงานบน Compositor Thread (GPU accelerated) และไม่ทำให้เกิด reflow
@keyframes scaleAnim {
30% { transform: scaleY(4); } /* จาก 100px เป็น 400px */
}