要在頁面上呈現比例、完成率、票數分布,條狀圖是最直覺的語言。而它的實作驚人地簡單——一個容器、一個方塊,寬度就是數值。
<div class="graph"> <strong class="bar" style="width: 24%;">24%</strong> </div>
外層 graph 是座標軸與軌道,內層 strong 是資料條。用 strong 而非空 div,是為了讓螢幕閱讀器能唸出百分比這個有意義的內容。
.graph {
position: relative; /* 給舊 IE 一個定位參照 */
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; }
三個細節值得注意。display:block 讓 strong 能接受寬度設定;line-height 等於 height,讓百分比數字垂直居中;外層的 position:relative 是給內部絕對定位元素一個參照,避免它一路定位到 body。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS 條狀圖表</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>
數值極小時文字會溢出。3% 的條子放不下「3%」這三個字,此時可以把文字移到條外,用 .graph .bar span { position:absolute; left:1em; } 讓數字掛在條子右側,或對極小值改用最小寬度。
行內 style 不適合大量資料。只有兩三條時寫 style="width:24%" 沒問題;若是幾十筆由後端輸出,該把寬度寫進 CSS 自訂屬性或用一組預先定義好的 class(.w10、.w25、.w50),樣式表才不會被行內宣告淹沒。