要在後台頁面顯示某個數值佔多少比例,條形圖比數字好懂。而它完全不需要繪圖函式庫——兩個 div、幾行 CSS,寬度百分比就是答案。
把「軌道」與「填充」分成兩層:外層負責畫框線與固定寬度,內層的 width 就是你要呈現的百分比。因為百分比是相對於父元素計算的,所以內層永遠落在軌道範圍內,超過 100% 就會自動被撐出——這也是為什麼要搭配 overflow:hidden 做保險。
<div class="graph"> <strong class="bar" style="width:24%">24%</strong> </div>
.graph {
position: relative; /* 讓內部定位有參照,舊 IE 尤其需要 */
width: 200px;
border: 1px solid #B1D632;
padding: 2px;
}
.graph .bar {
display: block; /* strong 預設是行內,必須轉成塊級才吃得到寬度 */
position: relative;
background: #B1D632;
text-align: center;
color: #333;
height: 2em;
line-height: 2em; /* 與 height 相同,文字垂直居中 */
}
.graph .bar span {
position: absolute;
left: 1em;
}
三個關鍵分別是:display:block 讓行內的 strong 能接受寬度;line-height 對齊 height 讓數字落在條子中央;外層 position:relative 提供定位原點。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>百分比條形圖</title>
<style type="text/css">
.graph { position: relative; width: 200px; border: 1px solid #B1D632; padding: 2px; }
.graph .bar {
display: block;
position: relative;
background: #B1D632;
text-align: center;
color: #333;
height: 2em;
line-height: 2em;
}
.graph .bar span { position: absolute; left: 1em; }
</style>
</head>
<body>
<div class="graph"><strong class="bar" style="width:24%">24%</strong></div>
<br />
<div class="graph"><strong class="bar" style="width:60%">60%</strong></div>
</body>
</html>
為可及性補上語意。純樣式的條子對螢幕閱讀器沒有意義。可以改用 role="progressbar" 並加上 aria-valuenow、aria-valuemin、aria-valuemax,讓輔助技術能正確朗讀進度。
極小數值會看不到。2% 的條子只有幾像素,文字根本放不下。做法是把數字移到條外(用內層 span 絕對定位到 left:100%),或給 min-width 一個下限。
避免大量行內樣式。資料筆數多時,改用 CSS 自訂屬性:<div class="bar" style="--v:24"> 搭配 width: calc(var(--v) * 1%),樣式表就能保持乾淨,後端輸出也更單純。