要呈現比例、排行或分布,不一定得請出圖表函式庫或圖片。只要善用百分比寬度、背景定位與絕對定位,純 CSS 也能畫出堪用的長條圖。以下三個範例由簡入繁。
外層是軌道,內層是填色區,寬度用行內樣式給百分比,數字直接當文字內容放進去。
<style>
.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; }
</style>
<div class="graph">
<strong class="bar" style="width: 24%;">24%</strong>
</div>
用定義清單 dl 語意化標示「項目—數值」的對應:dt 放標籤,dd 當軌道,內層 div 的寬度決定長度,strong 則以絕對定位掛在條末當刻度標記。
<style>
dl { margin: 0; padding: 0; }
dt {
position: relative;
clear: both;
display: block;
float: left;
width: 104px;
height: 20px;
line-height: 20px;
margin-right: 17px;
font-size: .75em;
text-align: right;
}
dd {
position: relative;
display: block;
float: left;
width: 197px;
height: 20px;
margin: 0 0 15px;
background: url("g_colorbar.jpg");
}
dd div {
position: relative;
background: url("g_colorbar2.jpg");
height: 20px;
width: 75%;
text-align: right;
}
dd div strong {
position: absolute;
right: -5px;
top: -2px;
display: block;
background: url("g_marker.gif");
height: 24px;
width: 9px;
text-indent: -9999px; /* 把文字推離視線,保留背景圖 */
overflow: hidden;
}
</style>
<dl>
<dt>Love Life</dt>
<dd><div style="width:25%;"><strong>25%</strong></div></dd>
<dt>Education</dt>
<dd><div style="width:55%;"><strong>55%</strong></div></dd>
<dt>War Craft 3 Rank</dt>
<dd><div style="width:75%;"><strong>75%</strong></div></dd>
</dl>
這裡用 text-indent:-9999px 搭配 overflow:hidden 把 strong 裡的文字藏起來、只留刻度圖形,是經典的圖文替換技巧。
改成直立式時,思維要從「寬度」換成「高度」,並以 bottom 為基準往上長。一張含五種顏色的精靈圖負責上色,background-position 決定取用哪一格。
<style>
#vertgraph {
width: 378px;
height: 207px;
position: relative;
background: url("g_backbar.gif") no-repeat;
}
#vertgraph ul {
width: 378px;
height: 207px;
margin: 0;
padding: 0;
}
#vertgraph ul li {
position: absolute;
width: 28px;
height: 160px;
bottom: 34px;
padding: 0 !important;
margin: 0 !important;
background: url("g_colorbar3.jpg") no-repeat !important;
text-align: center;
font-weight: bold;
color: white;
line-height: 2.5em;
}
#vertgraph li.critical { left: 24px; background-position: 0px !important; }
#vertgraph li.high { left: 101px; background-position: -28px !important; }
#vertgraph li.medium { left: 176px; background-position: -56px !important; }
#vertgraph li.low { left: 251px; background-position: -84px !important; }
#vertgraph li.info { left: 327px; background-position: -112px !important; }
</style>
<div id="vertgraph">
<ul>
<li class="critical" style="height: 150px;">22</li>
<li class="high" style="height: 80px;">7</li>
<li class="medium" style="height: 50px;">3</li>
<li class="low" style="height: 90px;">8</li>
<li class="info" style="height: 40px;">2</li>
</ul>
</div>
每根柱子的高度寫在行內樣式裡,其餘外觀全部交給 CSS。想改成資料驅動,只要用程式輸出 style="height: Npx" 這段即可,不必動到樣式表。
單一數值用第一種最省事;多項目橫向比較用第二種,語意清楚又方便加標籤;要強調排序與等級分層,第三種的直條圖最直觀。共同前提是數值範圍要先決定好,並在樣式中預留足夠的容器高度或寬度。