顯示經驗值、完成百分比、容量使用率,都可以做成進度條。最精簡的實作只需要一個外框 span 與一個內層 b,兩者共用同一張拼圖背景圖,靠位置錯開做出「底槽」與「填色」兩種狀態。
經驗值:
<span class="progress-bar"><b style="width:50px;"></b></span>
外層 span 是進度條的槽,內層 b 是填色的部分。改變 b 的 width,就改變了進度——整個元件沒有任何 JS。
.progress-bar, .progress-bar b{
background: url("/images/ico.png") no-repeat scroll 0 0;
display: block;
}
.progress-bar{
background-position: 0 0; /* 上半部:空的槽 */
height: 15px;
width: 430px;
}
.progress-bar b{
background-position: 0 -17px; /* 下半部:填色的部分 */
height: 12px;
}
附件圖:
這是典型的 CSS Sprite(精靈圖)應用。同一張圖檔裡,上方 15px 畫的是灰色底槽,下方從 -17px 開始畫的是彩色填色。透過 background-position 的 Y 軸偏移,讓兩個元素各自取用圖檔的不同區域,只發一次 HTTP 請求就完成兩種視覺。
內層 b 的 height 設為 12px(比外層的 15px 小),是為了讓填色不要蓋滿整個高度,視覺上更有層次。
今天不必再準備圖片,純 CSS 就能做出更好看的進度條:
.progress-bar{
width: 430px;
height: 15px;
background: #e6e6e6;
border-radius: 8px;
overflow: hidden;
}
.progress-bar b{
display: block;
height: 100%;
width: 50%;
background: linear-gradient(90deg, #4facfe, #00f2fe);
transition: width 0.3s ease;
}
改成純 CSS 後有三個好處:不必載入圖片、可以自由換色、加上 transition 就能讓進度變化有動畫。
純視覺的進度條對螢幕閱讀器毫無意義。若要正式使用,建議改用 HTML5 原生的 <progress> 元素,或幫容器補上 ARIA 屬性:
<div class="progress-bar" role="progressbar"
aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
<b style="width:50%"></b>
</div>
如此一來,輔具就能朗讀出「百分之五十」這樣的資訊。