萬盛學電腦網

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

CSS 實作長條圖表:純 CSS 打造資料視覺化

核心概念

利用容器固定寬度作為 100% 基準,內部區塊以百分比寬度呈現數值比例,配合邊框與背景色形成長條圖。

HTML 結構

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

CSS 樣式

.graph {
  position: relative; /* 修正 IE 定位基準 */
  width: 200px;       /* 圖表總寬度 = 100% */
  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; } /* 數值微調位置 */

完整範例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Bar Chart Demo</title>
<style>
.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>

進階擴充

  • 多組資料:在 .graph 內放多個 .bar,並設定 margin-bottom 間距。
  • 動畫效果:配合 transition: width 0.5s ease-out; 實現載入動畫。
  • 垂直長條圖:容器設 height,.bar 用 height 百分比與 position: absolute; bottom: 0。
  • 語意化標籤:可改用 <div role="progressbar" aria-valuenow="24" aria-valuemin="0" aria-valuemax="100"> 增強無障礙。

適用場景

簡易儀表板、技能熟練度展示、投票結果、載入進度條等輕量級資料視覺化需求,無需引入 Chart.js、D3.js 等重型庫。

copyright © 萬盛學電腦網 all rights reserved