CSS Spinner 載入動畫與轉圈圈 (Loading Animations)
當網頁在處理資料或載入圖片時,提供一個視覺化的載入提示(Loading Spinner)能大幅改善使用者體驗,讓使用者知道系統正在運行而非當機。
使用純 CSS 的 @keyframes,我們可以製作出各種輕量且美觀的載入動畫。
經典轉圈圈 (Spinner)
這是最常見的圓圈旋轉效果。
<div class="spinner"></div>
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3; /* 背景圓環顏色 */
border-top: 4px solid #3498db; /* 轉動部分的顏色 */
border-radius: 50%;
animation: spin 1s linear infinite; /* 無限循環旋轉 */
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
實作預覽
跳動的三個點 (Bouncing Dots)
常用於聊天機器人或簡潔的頁面載入。
<div class="dots">
<span></span>
<span></span>
<span></span>
</div>
.dots {
display: flex;
gap: 8px;
justify-content: center;
}
.dots span {
width: 12px;
height: 12px;
background-color: #3498db;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
}
/* 讓三個點有先後順序的延遲 */
.dots span:nth-child(1) { animation-delay: -0.32s; }
.dots span:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
實作預覽
雙環重疊動畫
更具現代感的多層旋轉。
<div class="double-ring">
<div></div>
<div></div>
</div>
.double-ring {
position: relative;
width: 60px;
height: 60px;
}
.double-ring div {
position: absolute;
width: 100%;
height: 100%;
border: 4px solid transparent;
border-top-color: #3498db;
border-radius: 50%;
animation: spin-double 1.5s cubic-bezier(0.5, 0, 0.5, 1) infinite;
}
.double-ring div:nth-child(2) {
width: 80%;
height: 80%;
top: 10%;
left: 10%;
border-top-color: #e74c3c;
animation-duration: 2s;
}
@keyframes spin-double {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
實作預覽
進度條動畫 (Progress Bar)
雖然這通常需要 JS 來控制真實進度,但我們可以用 CSS 製作一個「持續處理」的條狀動畫。
<div class="progress-container">
<div class="progress-bar"></div>
</div>
.progress-container {
width: 100%;
height: 10px;
background: #eee;
border-radius: 5px;
overflow: hidden;
}
.progress-bar {
width: 30%; /* 模擬進度 */
height: 100%;
background: linear-gradient(90deg, #3498db, #2980b9);
animation: move-progress 2s linear infinite;
}
@keyframes move-progress {
0% { transform: translateX(-100%); }
100% { transform: translateX(333%); }
}
實作預覽
重點提示
- 無限循環:載入動畫關鍵在於
animation-iteration-count: infinite,確保動畫不會停止。 - 顏色一致性:載入動畫的顏色應該符合品牌的視覺規範。
- 居中顯示:通常載入動畫需要放在容器的中央。你可以參考 CSS 置中 教學中關於
place-items: center的用法。
對於更複雜的 SVG 動畫,可以考慮使用 Lottie 或是專門的 SVG 動畫工具,但在大多數情況下,純 CSS 動畫對效能最為友善。