萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 條形圖表純前端實現:從基礎單條到複雜分組、垂直柱狀圖完整代碼

無需 Canvas、SVG、Chart.js,純 HTML + CSS 即可實現輕量級數據視覺化。本文遞進展示三種圖表形態完整代碼。

一、基礎單條橫向條形圖

<div class="graph">
  <strong class="bar" style="width: 24%;">24%</strong>
</div>

.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; }

核心:容器定寬,`.bar` 以百分比 `width` 映射數值,`line-height` 等高實現文字垂直置中。

二、複雜分組橫向條形圖(DL 列表語意化)

<dl class="chart">
  <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>

.chart dt {
  float: left; width: 104px; height: 20px; line-height: 20px;
  margin-right: 17px; font-size: .75em; text-align: right;
}
.chart dd {
  float: left; width: 197px; height: 20px; margin-bottom: 15px;
  background: url(g_colorbar.jpg);  /* 條軌背景 */
}
.chart dd div {
  height: 20px; background: url(g_colorbar2.jpg);  /* 實際進度條 */
  text-align: right;
}
.chart dd div strong {
  position: absolute; right: -5px; top: -2px;
  display: block; width: 9px; height: 24px;
  background: url(g_marker.gif);  /* 端點標記 */
  text-indent: -9999px; overflow: hidden;
}

特點:語意化 `

`、雙層背景圖區分軌道/進度、絕對定位端點標記。

三、垂直柱狀圖(絕對定位底部對齊)

<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>

#vertgraph {
  width: 378px; height: 207px; position: relative;
  background: url(g_backbar.gif) no-repeat;  /* 底部座標軸背景 */
}
#vertgraph ul { margin:0; padding:0; width:100%; height:100%; }
#vertgraph li {
  position: absolute; bottom: 34px; width: 28px;
  background: url(g_colorbar3.jpg) no-repeat;  /* 柱狀漸變圖 */
  text-align: center; font-weight: bold; color: white; line-height: 2.5em;
}
#vertgraph li.critical { left: 24px; background-position: 0; }
#vertgraph li.high { left: 101px; background-position: -28px; }
#vertgraph li.medium { left: 176px; background-position: -56px; }
#vertgraph li.low { left: 251px; background-position: -84px; }
#vertgraph li.info { left: 327px; background-position: -112px; }

核心:`bottom: 34px` 固定底部對齊,`height` 映射數值,`background-position` 切換顏色段。

進階增強建議

  1. CSS 變量驅動:`--value: 75%;` + `width: var(--value)`,JS 僅改變量
  2. 動畫過渡:`.bar { transition: width .6s ease-out; }`
  3. 無障礙:`
    ` 標籤文本 + `aria-label`、語意化結構
  4. 響應式:容器 `%` 寬度、媒體查詢調整柱寬/間距
  5. Tooltip:`:hover::after { content: attr(data-value); }` 純 CSS 提示

💡 適用場景:儀表盤輕量指標、後台統計卡片、靜態報表嵌入。複雜交互/大數據/實時流請用 Chart.js/ECharts/D3.js。

copyright © 萬盛學電腦網 all rights reserved