animation
1. CSS Animation
CSS Animation은 여러 스타일을 전환시킬 수 있으며, JavaScript 없이 요소에 애니메이션 효과를 적용할 때 사용합니다. 애니메이션을 나타내는 CSS 스타일과 애니메이션의 중간 상태를 나타내는 키프레임들로 이루어집니다.
1.1 transition vs animation
transition의 경우 요소의 상태가 변경되어야 애니메이션을 실행할 수 있지만, animation 속성은 요소의 상태 변화와 관계없이 애니메이션을 실행할 수 있습니다.
| transition | animation | |
|---|---|---|
| 시작시키는 것 | 상태 변화(:hover 등) | 선언만으로 자동(페이지가 뜨면 바로) |
| 중간 상태 | 시작과 끝, 둘 | @keyframes로 여러 개 |
| 반복·방향·멈춤 | 없음 | 있음 |
마우스를 올렸을 때처럼 상태가 바뀔 때 한 번 부드럽게 바뀌게 하려면 transition, 계속 도는 것이나 페이지가 열리면서 처음 나타나는 효과는 animation이 맞습니다.
1.2 @keyframes
@keyframes는 두 개 이상의 애니메이션 중간 상태를 설정합니다. 0%는 시작점, 100%는 종료 시점을 의미하며, from과 to로도 표현할 수 있습니다. @keyframes 뒤의 이름(animation-name 자리)은 마음대로 지을 수 있습니다.
@keyframes animation-name {
from {
/* 시작 상태 */
}
to {
/* 종료 상태 */
}
}
/* 또는 */
@keyframes animation-name {
0% {
/* 시작 상태 */
}
50% {
/* 중간 상태 */
}
100% {
/* 종료 상태 */
}
}
@keyframes만 써서는 아무 일도 일어나지 않습니다. 요소에 animation으로 그 이름과 시간을 이어 줘야 움직입니다. animation-duration의 기본값은 0s라서 시간을 빼먹으면 보이지 않습니다. 가장 단순한 예로, 상자가 오른쪽으로 갔다가 돌아오는 것을 만들어 봅니다. from을 생략하면 요소에 지금 적용된 스타일이 시작 상태가 됩니다.
<div class="slider"></div>
@keyframes slide {
to {
transform: translateX(200px);
}
}
.slider {
width: 60px;
height: 60px;
background-color: #3498db;
animation: slide 2s infinite alternate;
}
이제 키프레임에 steps()와 background-position을 더해 캐릭터를 걷게 만들어 봅니다. 먼저 쓸 이미지입니다.

이 이미지는 스프라이트 시트입니다. 캐릭터의 동작을 한 컷씩 가로로 이어 붙인 그림 한 장이고, 이 시트는 라이캣이 걷는 동작 7컷입니다. 이 이미지를 사용해서 라이캣이 걷는 모션을 @keyframes를 사용해 구현해보았습니다. 코드를 간단히 살펴보겠습니다.
<div class="licat"></div>
@keyframes move-licat {
to {
background-position: right 0;
}
}
.licat {
width: 168px;
height: 200px;
background: url('/images/html-css/chapter15/02.png') no-repeat 0 0 / auto 100%;
animation: move-licat 0.8s infinite steps(6);
}
.licat 요소의 크기는 width: 168px;와 height: 200px;로 설정되어 있습니다. 시트 한 컷만 들여다보는 창이라고 생각하면 됩니다. background 속성은 스프라이트 이미지를 설정하고 그 초기 위치를 지정합니다. 배경 이미지 위치와 관련하여, 0 0은 스프라이트 시트의 시작점인 왼쪽 상단 모서리를, 50% 50%는 이미지의 중앙을, 그리고 100% 100%는 오른쪽 하단 모서리를 나타냅니다. 특히 background-position: 0 0은 스프라이트 시트의 첫 번째 컷을 표시하는 데 사용됩니다.
background-size: auto 100%; 는 스프라이트 이미지의 높이를 요소에 맞추고 너비는 자동으로 조정하도록 설정합니다. 그러면 컷 하나가 창 하나(168px)와 같은 크기가 됩니다.
![]()
위 그림은 이 코드의 움직임을 단계별로 보여 줍니다. 키프레임이 background-position을 right 0까지 옮깁니다. right 0은 시트의 오른쪽 끝을 창의 오른쪽 끝에 맞추라는 뜻이라서, 시트는 왼쪽으로 시트 폭에서 창 폭을 뺀 만큼, 곧 컷 6개 분량 밀립니다. steps(6)은 이 이동을 6번에 나눠 끊어서 하므로, 시트가 컷 하나씩 6번 밀리면서 창에는 1번부터 6번 컷이 차례로 보입니다. 부드럽게 이어서 움직이는 대신 컷이 뚝뚝 바뀌기 때문에 걷는 동작처럼 보입니다. 7번째 컷은 이동이 끝나는 지점에 해당하는데, 그 순간 애니메이션이 처음으로 돌아가므로 보이지 않습니다.
더 해 보기
위 코드의 steps(6)을 steps(7, jump-none)으로 바꿔 보세요. jump-none은 처음과 끝 값을 모두 보여 주는 방식이라, 7컷이 모두 차례로 나옵니다.
1.3 animation 속성
1.3.1 animation-name
애니메이션의 이름을 지정합니다. 이름은 글자(한글도 됩니다), 언더바(_), 하이픈(-)으로 시작해야 하고 숫자나 # 같은 기호로 시작할 수 없습니다. 대소문자를 구분하므로(Name과 name은 다른 이름) 헷갈리지 않게 보통 소문자로 씁니다.
@keyframes animation-name {
}
/* 옳은 예 */
name
_name
-name
/* 나쁜 예 */
#name
1name
/* 쓸 수는 있지만 권장하지 않음: 대소문자를 구분하므로 다른 곳에서 name으로 부르면 찾지 못함 */
Name
1.3.2 animation-duration
애니메이션이 한 사이클을 완료하는 데 걸리는 시간을 지정합니다. 단위는 초(s) 또는 밀리초(ms)를 사용합니다. 기본값은 0s라서 시간을 쓰지 않으면 애니메이션이 보이지 않습니다. 음수는 잘못된 값이라 그 선언이 무시됩니다.
animation-duration: 0.1s;
animation-duration: 100ms;
1.3.3 animation-timing-function
애니메이션의 진행 속도를 제어하는 속성입니다.
ease: 기본값. 애니메이션이 중간에 빨라졌다 끝에서 느려지는 자연스러운 움직임을 만듭니다.linear: 애니메이션이 일정한 속도로 진행됩니다.steps(n): 애니메이션이 n개의 단계로 나뉘어 진행됩니다.cubic-bezier: 복잡한 속도 변화를 가능하게 합니다. 네 숫자의 뜻은 15-2에서 설명했습니다.
animation-timing-function: ease;
animation-timing-function: cubic-bezier(0.1, 0.7, 1, 0.1);
animation-timing-function: steps(4);
키프레임이 셋 이상이면
transition은 시작과 끝 사이에 한 번만 timing-function을 적용하지만, animation의 animation-timing-function은 애니메이션 전체가 아니라 키프레임 사이 구간마다 적용됩니다. 0%, 50%, 100% 키프레임이 있으면 0%에서 50%, 50%에서 100% 두 구간이 각각 ease로 시작해서 끝나므로, 50% 지점에서 한 번 느려졌다 다시 출발하듯 보입니다. 전체를 같은 속도로 보이게 하려면 linear를 쓰고, 구간마다 움직이는 거리가 같도록 키프레임 위치도 맞춥니다.
크롬 개발자 도구에서 다양한 속성을 확인할 수 있습니다.

1.3.4 animation-delay
애니메이션 시작 시점을 지정합니다. 양수 값을 사용하면 지정된 시간 후에 애니메이션이 시작되고, 음수 값을 사용하면 애니메이션이 이미 진행 중인 것처럼 중간부터 시작됩니다. 예를 들어, -1s 값을 지정하면 애니메이션이 1초 지점부터 즉시 시작됩니다. 같은 애니메이션을 여러 요소에 걸면서 요소마다 다른 음수 delay를 주면, 처음부터 각자 다른 지점에서 진행 중인 것처럼 시작하므로, 요소들이 한꺼번에 같은 동작을 하지 않고 어긋나게 움직이는 효과를 만들 수 있습니다.
animation-delay: 3s;
animation-delay: -1500ms;
/* 음수값: 애니메이션이 중간부터 시작 */
1.3.5 animation-iteration-count
애니메이션 재생 횟수를 설정합니다. infinite로 설정하면 애니메이션이 무한히 반복됩니다.
animation-iteration-count: 3;
animation-iteration-count: infinite;
1.3.6 animation-direction
애니메이션의 재생 방향을 지정합니다.
normal: 기본값. 정방향으로 재생됩니다.reverse: 역방향으로 재생됩니다.alternate: 정방향과 역방향을 번갈아가며 재생합니다.alternate-reverse: 역방향과 정방향을 번갈아가며 재생합니다.
animation-direction: normal;
animation-direction: reverse;
animation-direction: alternate;
animation-direction: alternate-reverse;
같은 키프레임에 방향만 다르게 준 네 상자를 비교해 보세요. normal과 reverse는 끝에서 처음으로 한 번에 돌아가고, alternate는 왕복합니다.
<div class="dir dir-normal">normal</div>
<div class="dir dir-reverse">reverse</div>
<div class="dir dir-alternate">alternate</div>
<div class="dir dir-alternate-reverse">alternate-reverse</div>
@keyframes dir-move {
from {
transform: translateX(0);
}
to {
transform: translateX(200px);
}
}
.dir {
width: 150px;
height: 32px;
margin-bottom: 6px;
background-color: #3498db;
color: white;
font-size: 13px;
line-height: 32px;
text-align: center;
animation: dir-move 2s linear infinite;
}
.dir-normal {
animation-direction: normal;
}
.dir-reverse {
animation-direction: reverse;
}
.dir-alternate {
animation-direction: alternate;
}
.dir-alternate-reverse {
animation-direction: alternate-reverse;
}
1.3.7 animation-fill-mode
애니메이션 실행 전과 후에 대상에 스타일을 적용하는 방법을 지정합니다.
none: 기본값. 애니메이션이 실행되지 않을 때(시작 전과 끝난 뒤)는 키프레임 스타일이 적용되지 않습니다. (normal이라는 값은 없습니다.)forwards: 애니메이션이 끝난 후 마지막 키프레임의 스타일을 유지합니다.backwards: 애니메이션이 시작되기 전에 첫 번째 키프레임의 스타일을 적용합니다.both:forwards와backwards를 모두 적용합니다.
<div></div>
div {
width: 100px;
height: 100px;
background-color: skyblue;
animation: example 3s 2s backwards;
}
@keyframes example {
0% {
margin-left: 40%;
background-color: royalblue;
}
50% {
margin-left: 0%;
background-color: royalblue;
}
100% {
margin-left: 80%;
background-color: royalblue;
}
}
animation: example 3s 2s backwards에서 시간 값이 둘이면 첫째가 animation-duration(3초 동안 재생), 둘째가 animation-delay(2초 뒤에 시작)입니다. 그래서 이 상자는 시작을 기다리는 2초 동안 backwards 덕에 첫 키프레임(royalblue, margin-left: 40%)으로 미리 가 있다가 움직이기 시작합니다.
같은 키프레임에 값만 바꿔 네 가지를 나란히 비교해 봅니다. 애니메이션은 2초 기다렸다가 2초 동안 진행한 뒤 끝납니다. 한 번만 재생되므로 다시 보려면 코드를 아무 곳이나 고쳐 다시 실행하세요.
<div class="fill fill-none">none</div>
<div class="fill fill-forwards">forwards</div>
<div class="fill fill-backwards">backwards</div>
<div class="fill fill-both">both</div>
@keyframes fill-move {
from {
transform: translateX(100px);
background-color: tomato;
}
to {
transform: translateX(200px);
background-color: royalblue;
}
}
.fill {
width: 100px;
height: 32px;
margin-bottom: 6px;
background-color: skyblue;
color: white;
font-size: 13px;
line-height: 32px;
text-align: center;
animation-name: fill-move;
animation-duration: 2s;
animation-delay: 2s;
}
.fill-none {
animation-fill-mode: none;
}
.fill-forwards {
animation-fill-mode: forwards;
}
.fill-backwards {
animation-fill-mode: backwards;
}
.fill-both {
animation-fill-mode: both;
}
backwards와 both는 기다리는 2초 동안 붉은색(tomato)으로 오른쪽 100px에 미리 가 있고, forwards와 both는 끝난 뒤에도 파란색(royalblue)으로 오른쪽 200px에 남습니다. none은 기다리는 동안도, 끝난 뒤도 원래 자리의 하늘색으로 있습니다.
1.3.8 animation-play-state
애니메이션의 재생 상태를 설정합니다.
paused: 애니메이션을 일시 정지시킵니다.running: 애니메이션을 재생시킵니다.
animation-play-state: running; /* 기본값 */
animation-play-state: paused;
마우스를 올리면 멈추는 예제입니다. 마우스를 내리면 멈춘 자리에서 다시 움직입니다.
<div class="runner">마우스를 올려 보세요</div>
@keyframes run {
from {
transform: translateX(0);
}
to {
transform: translateX(120px);
}
}
.runner {
width: 160px;
height: 40px;
background-color: #3498db;
color: white;
font-size: 13px;
line-height: 40px;
text-align: center;
animation: run 2s linear infinite alternate;
}
.runner:hover {
animation-play-state: paused;
}
1.3.9 animation (단축 속성)
모든 animation 관련 속성을 한 번에 설정할 수 있습니다.
animation: name duration timing-function delay iteration-count direction
fill-mode play-state;
위 순서는 읽기 쉬운 관례일 뿐, 이름 외에는 순서가 자유롭습니다. transition처럼 시간 값이 둘이면 첫 번째가 duration, 두 번째가 delay입니다. 예를 들어 animation: move 2s ease-in 1s 3 alternate;는 1초 기다린 뒤, 한 번에 2초씩 정방향, 역방향, 정방향으로 모두 3번 재생합니다. 세 번 왕복하게 하려면 횟수를 6으로 씁니다.
팁
Chrome 개발자 도구의 Elements 탭에서 요소를 선택하고 Styles 패널의 animation 선언을 고쳐 보면 결과가 바로 화면에 나옵니다. 속도 곡선은 animation-timing-function 값 옆의 곡선 아이콘을 누르면 편집기가 열려 곡선을 끌어서 조정할 수 있습니다.
움직임을 줄여 달라는 사용자 설정 존중하기
어지럼증이나 전정 기관 장애가 있는 사용자는 운영체제에서 '동작 줄이기'를 켜 둡니다. CSS에서는 prefers-reduced-motion 미디어 쿼리로 이 설정을 알 수 있으므로, 크게 움직이는 애니메이션은 이 설정이 켜져 있을 때 멈추거나 줄입니다. @media는 16-3에서 자세히 배웁니다.
@media (prefers-reduced-motion: reduce) {
.licat {
animation: none;
}
}
1.4 실습 시계 초침, 분침, 시침 만들기
아래와 같은 모양의 위젯을 만들고 시계처럼 돌아가는 애니메이션을 만들어보세요. 단, 실제 시계처럼 정확히 동작할 필요는 없습니다.

그림의 초록·검정·빨강 막대가 세 개의 침입니다. 길이와 색은 직접 정해도 됩니다. 이 장에서 배운 transform-origin, rotate, @keyframes, animation을 모두 쓰는 마무리 실습입니다.
힌트
- 침은
div하나씩, 모두 세 개입니다. 시계 판의 가운데에 겹쳐 놓습니다. - 침이 도는 기준점은 침의 한쪽 끝이어야 합니다. 어떤 속성으로 정했었는지 생각해 보세요.
- 한 바퀴(360도)를 도는 시간은 초침 60초, 분침 3600초(1시간), 시침 43200초(12시간)입니다. 일정한 속도로 계속 돌려야 합니다.
먼저 직접 만들어 본 뒤 열어 보세요.
시계 실습 한 예 보기
<div class="clock">
<div class="hand hour"></div>
<div class="hand min"></div>
<div class="hand sec"></div>
</div>
.clock {
position: relative;
width: 200px;
height: 200px;
border-radius: 30%;
background-color: royalblue;
}
.hand {
position: absolute;
top: 50%;
left: 50%;
height: 6px;
margin-top: -3px;
transform-origin: left center;
animation: spin linear infinite;
}
.sec {
width: 80px;
background-color: red;
animation-duration: 60s;
}
.min {
width: 70px;
background-color: black;
animation-duration: 3600s;
}
.hour {
width: 50px;
background-color: green;
animation-duration: 43200s;
}
@keyframes spin {
from {
transform: rotate(-90deg);
}
to {
transform: rotate(270deg);
}
}
침은 12시 방향에서 시작하도록 -90deg에서 270deg까지 돕니다. rotate(0deg)는 오른쪽(3시 방향)을 가리키기 때문입니다. 침의 길이만 다르고 모양은 같아서, 공통 스타일을 .hand에 두고 .sec(빨강), .min(검정), .hour(초록)가 길이·색·한 바퀴 시간만 정했습니다.
마지막 수정