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

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

ตัวอย่างการสร้างแอนิเมชันกับคุณสมบัติ margin แบบ shorthand (ทั้ง 4 ด้านพร้อมกัน)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    p {
      animation: mymove 3s infinite;
      margin: 20px;
    }
    @keyframes mymove {
      70% {
        margin: 60px;
      }
    }
  </style>
</head>
<body>
  <p>This is demo text! This is demo text! This is demo text! This is demo text! This is demo text! This is demo text! This is demo text! This is demo text! This is demo text!</p>
</body>
</html>

คำอธิบาย: พารากราฟเริ่มต้นมี margin 20px ทุกด้าน ที่ 70% จะขยายเป็น 60px ทุกด้าน ทำให้กล่องดูใหญ่ขึ้นและเนื้อหารอบๆ ถูกผลักออกไป

ข้อจำกัด: การ animate shorthand margin จะ animate ทุกด้านพร้อมกัน ไม่สามารถควบคุมแต่ละด้านแยกกันได้ใน keyframe เดียวกัน (ต้องแยก keyframe หรือใช้ longhand properties)

แนวทางที่ดีกว่า: ใช้ transform: scale() สำหรับการขยายขนาด หรือ animate margin-top, margin-right แยกกันหากต้องการควบคุมทิศทาง