css制作散点图
使用纯CSS制作散点图
通过CSS的flexbox或grid布局结合伪元素实现简单的散点图。以下是一个基于flexbox的示例:
<div class="scatter-plot">
<div class="point" style="--x: 20%; --y: 30%;"></div>
<div class="point" style="--x: 50%; --y: 80%;"></div>
<div class="point" style="--x: 70%; --y: 10%;"></div>
</div>
.scatter-plot {
position: relative;
width: 300px;
height: 200px;
background-color: #f0f0f0;
border: 1px solid #ccc;
}
.point {
position: absolute;
width: 10px;
height: 10px;
background-color: #ff6b6b;
border-radius: 50%;
left: var(--x);
top: var(--y);
transform: translate(-50%, -50%);
}
结合CSS变量动态控制
通过CSS变量实现动态调整散点位置和样式:

:root {
--point-color: #4d96ff;
--point-size: 8px;
}
.point {
width: var(--point-size);
height: var(--point-size);
background-color: var(--point-color);
}
添加动画效果
为散点添加悬停动画增强交互性:

.point {
transition: transform 0.3s, background-color 0.3s;
}
.point:hover {
transform: translate(-50%, -50%) scale(1.5);
background-color: #ff0000;
}
响应式散点图
使用vw/vh单位实现响应式布局:
.scatter-plot {
width: 80vw;
height: 60vh;
}
高级技巧:伪元素生成散点
通过::before伪元素减少HTML标签数量:
<div class="scatter-plot">
<div class="point-container" style="--x: 20%; --y: 30%;"></div>
</div>
.point-container::before {
content: '';
position: absolute;
width: 10px;
height: 10px;
background: #000;
border-radius: 50%;
left: var(--x);
top: var(--y);
}
注意事项
- 坐标系原点在容器左上角,Y轴向下为正方向
- 百分比单位基于父容器尺寸计算
transform: translate(-50%, -50%)确保点中心对准坐标位置- 复杂数据可视化建议使用SVG或Canvas实现






