프론트엔드/CS

[CSS - Keyframes] 로딩 애니메이션(사각형 회전 이동, 색상 변화)

턴태 2022. 9. 23. 16:16

See the Pen test1 by seongtae (@stae1102) on CodePen.

로딩 애니메이션 두 번째 입니다. 사각형이 각각 위치를 옮겨가며 색상을 바꿉니다.

 

여기서 사용하는 것은 position 속성과 background-color 속성입니다.

 

1. HTML 작성

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="css/style.css">
</head>

<body>

  <div class="loading">
    <span></span>
    <span></span>
  </div>

</body>

</html>

HTML의 구조를 보면

└ div .loading
	├ span
    └ span

이렇게 class가 "loading"인 div 태그 아래 자식으로 span 태그를 두 개 갖고 있습니다.

div 태그는 두 개의 태그를 감싸고 포지션을 사용하기 위함입니다.

 

2. CSS 작성

2-1. 기본 구조

.loading {
  width: 100px;
  height: 100px;
  position: relative;
}
.loading span {
  position: absolute;
  width: 30px;
  height: 30px;
  background-color: grey;
  top: 0;
  left: 0;
  animation: loading 1.5s infinite;
}

div 태그의 크기를 정해주고 반드시 position 속성의 값을 relative로 작성해야 합니다. 자식 요소가 부모의 위치를 참고하여 위치를 변경해야 하기 때문입니다.

 

그 다음 div 태그 아래의 span 태그의 공통 속성을 작성해줍니다. top과 left에 각각 0을 넣어서 좌상단에서 애니메이션이 시작하도록 합니다.

 

2-2. 애니메이션

이제 animation-name 에 사용된 loading 애니메이션을 정의합니다.

@keyframes loading {
  0%,
  100% {
    top: 0;
    left: 0;
    background-color: red;
  }
  25% {
    top: 0;
    left: calc(100% - 10px);
    background-color: dodgerblue;
  }
  50% {
    top: calc(100% - 10px);
    left: calc(100% - 10px);
    background-color: orange;
  }
  75% {
    top: calc(100% - 10px);
    left: 0;
    background-color: yellowgreen;
  }
}

가장 중요한 것은 이동입니다. 4번의 움직임에서 시계방향으로 span 도형들이 움직일 수 있도록 합니다. 그리고 각각 색상도 바꿉니다.

 

2-3. 딜레이 추가

이제 두 도형이 돌 수 있도록 작성합니다.

.loading span:nth-child(2) {
	animation-delay: .75s;
}

이렇게 하면 두 도형이 시간차를 갖고 애니메이션을 진행하기 때문에 자연스럽게 서로 회전합니다.