條狀圖表是網頁設計中很常遇到的一種表現形式,能把數量以長條圖形直觀呈現。它不需要任何 JavaScript,單靠 CSS 就能完成。
<div class="graph">
<strong class="bar" style="width: 24%;">24%</strong>
</div>
一個外層容器 graph,裡面放一個 strong 並套用 bar 類,數值文字直接寫在標籤內。
.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; }
外層的 border 與 padding 勾出座標軸範圍,bar 則靠 display: block 撐成橫條。真正的關鍵只有一個:width 用百分比寫在行內樣式上,比例就直接對應到容器寬度。height 與 line-height 同為 2em,讓百分比數字正好落在色條中間。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; 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>
這個模式可以再往外延伸:多組圖表並排時,把寬度與顏色抽成 class,就能量產整頁的統計視覺;若要加上刻度線,替 .graph 鋪一張縱向重複的背景圖即可,結構完全不用改。