Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การสร้างแอนิเมชันสำหรับคุณสมบัติ CSS width

ตัวอย่างพื้นฐานของการสร้างแอนิเมชันเปลี่ยนความกว้าง (width) ของ element

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 300px;
      height: 250px;
      background-color: maroon;
      color: white;
      animation: myanim 3s;
    }
    @keyframes myanim {
      30% {
        width: 500px;
      }
    }
  </style>
</head>
<body>
  <h1>CSS width property</h1>
  <div>
    <h1>This is demo text!</h1>
  </div>
</body>
</html>

คำอธิบาย: กล่องเริ่มต้นกว้าง 300px ที่ 30% ของแอนิเมชัน 3 วินาที จะขยายกว้างเป็น 500px แล้วจบ (ไม่มี infinite) จะค้างที่ 500px (หรือกลับไป 300px ขึ้นอยู่กับ fill-mode)

ข้อควรระวังด้านประสิทธิภาพ: การ animate width ทำให้เกิด Layout Reflow ทุกเฟรม ต้นทุนสูง ส่งผลต่อ element อื่นใน flow

แนวทางที่ดีกว่า (Best Practice): ใช้ transform: scaleX() แทน

div {
  width: 300px;
  transform-origin: left center; /* ขยายจากซ้าย */
  animation: scaleX 3s;
}
@keyframes scaleX {
  30% { transform: scaleX(1.67); } /* 300 * 1.67 ≈ 500 */
}

วิธีนี้ GPU accelerated ไม่ทำ reflow ราบรื่นกว่ามาก