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

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

ตัวอย่างการสร้างแอนิเมชันเปลี่ยนระยะห่างซ้าย (margin-left) ของ element

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

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      background-color: gray;
      animation: myanim 3s infinite;
      color: white;
    }
    @keyframes myanim {
      30% {
        margin-left: 20px;
      }
    }
  </style>
</head>
<body>
  <h2>Heading One</h2>
  <div>
    This is demo text.
  </div>
</body>
</html>

คำอธิบาย: กล่องสีเทาเริ่มต้นไม่มี margin-left ที่ 30% จะเลื่อนขวา 20px (เพิ่ม margin-left) แล้วกลับมา

ข้อควรระวัง: การ animate margin-left ก่อให้เกิด layout reflow เหมือน margin อื่นๆ

แนวทางที่ดีกว่า: ใช้ transform: translateX(20px) แทน ซึ่งราบรื่นกว่าและไม่ส่งผลต่อ layout ของ element อื่น

@keyframes betterSlide {
  30% { transform: translateX(20px); }
}