CSS로 애니메이션 역방향 먼저 실행 후 순방향 전환하기
애니메이션을 먼저 역방향(뒤쪽)으로 실행한 다음 순방향(앞쪽)으로 실행하려면 CSS의 animation-direction 속성을 사용합니다. 이 속성에 alternate-reverse 값을 지정하면 첫 번째 사이클은 역방향으로 시작되고, 이후 사이클부터는 순방향과 역방향이 번갈아가며 재생됩니다.
animation-direction 속성의 주요 값
- normal: 기본값으로, 항상 정방향으로 재생합니다.
- reverse: 항상 역방향으로 재생합니다.
- alternate: 정방향과 역방향을 번갈아가며 재생합니다.
- alternate-reverse: 역방향으로 시작하여 정방향과 번갈아가며 재생합니다.
예제
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 200px;
position: relative;
background-color: yellow;
animation-name: myanim;
animation-duration: 2s;
animation-direction: alternate-reverse;
animation-iteration-count: 3;
}
@keyframes myanim {
0% {background-color:green; left:0px; top:0px;}
50% {background-color:maroon; left:100px; top:100px;}
100% {background-color:gray; left:0px; top:0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
코드 설명
위 예제에서 @keyframes myanim은 요소의 배경색과 위치가 변화하는 애니메이션을 정의합니다. animation-duration: 2s는 한 사이클의 재생 시간을 2초로 설정하며, animation-iteration-count: 3은 애니메이션을 총 3회 반복하도록 지정합니다.
핵심은 animation-direction: alternate-reverse; 부분입니다. 이 설정 덕분에 애니메이션이 일반적인 정방향(0% → 100%)이 아닌 역방향(100% → 0%)으로 먼저 시작되고, 이후에는 정방향과 역방향이 교대로 반복 재생됩니다. 결과적으로 초록색에서 시작하지 않고 회색 상태에서 역방향으로 움직이는 것을 확인할 수 있습니다.