---
# System prepended metadata

title: 用 CSS 實作載入動畫
tags: [note]

---

# 用 CSS 實作載入動畫

Elantris

[TOC]

---

## 實作

<style>
  .loading {
    position: relative;
    width: 16rem;
    height: 3rem;
    overflow: hidden;
    border: 2px solid black;
    border-radius: 0.5rem;
    background: white;
  }
  .loading-1::before {
    content: "";
    position: absolute;
    top: 0.25rem;
    bottom: 0.25rem;
    left: 0;
    width: 100%;
    background: black;
  }
  @keyframes growWidth {
    from {
      width: 0;
    }
    to {
      width: 100%;
    }
  }
  .loading-2::before {
    animation-name: growWidth;
    animation-duration: 4s;
    animation-timing-function: steps(10, jump-start);
    animation-iteration-count: infinite;
  }
  .loading-3::after {
    content: "";
    position: absolute;
    inset: 0;
    background-image: linear-gradient(to right, white 0%, white 25%, transparent 25%, transparent 75%, white 75%);
    background-size: 10% 100%;
  }
</style>

### 外框

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

```css
.loading {
  position: relative;
  width: 16rem;
  height: 3rem;
  border: 2px solid black;
  border-radius: 0.5rem;
  background: white;
}
```

### 進度條

1. 內層有顏色、會變動的部分
2. 定位左上、左下為起始點
3. width 100% 為可變動值

<div class="loading loading-1"></div>

```css
.loading::before {
  content: "";
  position: absolute;
  top: 0.25rem;
  bottom: 0.25rem;
  left: 0;
  width: 100%;
  background: black;
}
```

### 動畫

1. 用動畫改變 width
2. timing-function 用 steps() 製造頓點

<div class="loading loading-1 loading-2"></div>

```css
@keyframes growWidth {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
.loading::before {
  /* ... */
  animation-name: growWidth;
  animation-duration: 4s;
  animation-timing-function: steps(10, jump-start);
  animation-iteration-count: infinite;
}
```


### 遮罩

1. 用漸層背景製造白色、透明區塊
2. background-size 設為 10% 製造一排透明窗戶蓋在最上方

<div class="loading loading-1 loading-2 loading-3"></div>

```css
.loading::after {
  content: "";
  position: absolute;
  inset: 0;
  background-image: linear-gradient(to right, white 0%, white 25%, transparent 25%, transparent 75%, white 75%);
  background-size: 10% 100%;
}
```

## 完整程式碼

[Pure CSS Loading Bar](https://codepen.io/Elantris/pen/gONgVEY)
