ตัวอย่างการสร้างแอนิเมชันเลื่อน element แนวนอนด้วยคุณสมบัติ left (ต้องใช้ร่วมกับ position: absolute/relative/fixed)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid black;
width: 300px;
height: 100px;
position: absolute;
left: 0;
animation: myanim 5s infinite;
}
@keyframes myanim {
30% {
left: 200px;
}
}
</style>
</head>
<body>
<div>This is demo text</div>
</body>
</html>
คำอธิบาย: กล่องเริ่มต้นอยู่ซ้ายสุด (left: 0) ที่ 30% จะเลื่อนไปขวา 200px แล้วกลับมา
ข้อควรระวัง: เหมือน height/width การ animate left/top/right/bottom ก่อให้เกิด Layout Reflow และไม่ได้รับการ GPU acceleration
แนวทางปฏิบัติที่ดีที่สุด (Best Practice): ใช้ transform: translateX() แทน
div {
position: absolute;
left: 0; /* ตำแหน่งเริ่มต้น */
animation: slide 5s infinite;
}
@keyframes slide {
30% { transform: translateX(200px); }
}
วิธีนี้ราบรื่นกว่า ใช้ทรัพยากรน้อยกว่า และไม่ส่งผลต่อ layout ของ element อื่น