css 制作图表
CSS 制作图表的方法
CSS 可以用来制作多种类型的图表,包括条形图、饼图、折线图等。以下是几种常见的实现方式:
条形图
使用 div 元素和 CSS 的 height 属性可以轻松创建条形图。通过调整高度和背景色,可以直观地展示数据。
<div class="bar-chart">
<div class="bar" style="height: 40%; background-color: #3498db;"></div>
<div class="bar" style="height: 70%; background-color: #e74c3c;"></div>
<div class="bar" style="height: 30%; background-color: #2ecc71;"></div>
</div>
.bar-chart {
display: flex;
height: 200px;
align-items: flex-end;
gap: 10px;
}
.bar {
width: 50px;
transition: height 0.3s ease;
}
饼图
使用 CSS 的 conic-gradient 可以创建饼图。通过设置不同颜色的角度来展示比例。
<div class="pie-chart"></div>
.pie-chart {
width: 200px;
height: 200px;
border-radius: 50%;
background: conic-gradient(
#3498db 0% 40%,
#e74c3c 40% 70%,
#2ecc71 70% 100%
);
}
折线图
折线图可以通过 SVG 结合 CSS 实现,但纯 CSS 也可以使用伪元素和 transform 属性模拟。
<div class="line-chart">
<div class="point" style="left: 10%; bottom: 20%;"></div>
<div class="point" style="left: 30%; bottom: 50%;"></div>
<div class="point" style="left: 50%; bottom: 30%;"></div>
<div class="point" style="left: 70%; bottom: 70%;"></div>
<div class="point" style="left: 90%; bottom: 40%;"></div>
</div>
.line-chart {
position: relative;
height: 200px;
width: 100%;
border-bottom: 2px solid #333;
border-left: 2px solid #333;
}
.point {
position: absolute;
width: 10px;
height: 10px;
background-color: #e74c3c;
border-radius: 50%;
transform: translate(-50%, 50%);
}
.point::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 1000px;
height: 2px;
background-color: #3498db;
transform-origin: left;
}
动画效果
为图表添加动画效果可以提升用户体验。使用 transition 或 @keyframes 实现平滑过渡。

.bar {
transition: height 0.5s ease;
}
@keyframes grow {
from { height: 0%; }
to { height: var(--target-height); }
}
.bar {
animation: grow 1s forwards;
}
注意事项
- 纯 CSS 图表适合简单数据展示,复杂需求可能需要结合 JavaScript 或库(如 Chart.js)。
- 确保图表在不同设备上响应式适配,使用相对单位(如
%或vw)。 - 考虑无障碍访问,为图表添加
aria-label或隐藏的文本描述。
通过以上方法,可以灵活地用 CSS 实现多种图表效果。






