在网页中,我们常常需要用到概览图来展示数据的分布情况。而制作概览图的一种比较简单的方式就是使用CSS来绘制XY坐标系。 .chart { : relative; width: 600px; heigh...
在网页中,我们常常需要用到概览图来展示数据的分布情况。而制作概览图的一种比较简单的方式就是使用CSS来绘制XY坐标系。
.chart {
position: relative;
width: 600px;
height: 400px;
border: 1px solid #ccc;
margin: 20px auto;
}
.chart:before {
content: ';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
box-sizing: border-box;
padding: 50px;
border: 1px solid #ccc;
}
.chart .y-axis {
position: absolute;
top: 50px;
left: 50px;
bottom: 50px;
width: 1px;
background-color: black;
}
.chart .x-axis {
position: absolute;
bottom: 50px;
right: 50px;
left: 50px;
height: 1px;
background-color: black;
}
.chart .y-label {
position: absolute;
top: 0;
left: 10px;
font-size: 12px;
font-weight: bold;
transform: rotate(-90deg);
}
.chart .x-label {
position: absolute;
bottom: -20px;
left: 50%;
transform: translateX(-50%);
font-size: 12px;
font-weight: bold;
} 上面这段CSS代码实现了一个基础的XY坐标系。我们首先定义了一个.chart类来设置整个概览图的宽高和边框等基础样式。接着我们使用伪类:before来绘制XY坐标系的边框,并且设置了padding值使得边框内部能够容纳其他元素。
然后我们定义了.y-axis和.x-axis类分别用来绘制Y轴和X轴,它们都是绝对定位的,并且通过top、bottom和right、left来设置位置和宽高。注意到Y轴只有一个1像素的竖线,而X轴只有一个1像素的横线。
最后我们定义了.y-label和.x-label类用于标记坐标轴,它们也是绝对定位的,但是它们的位置比较特殊,需要通过transform来旋转或平移。
使用上述CSS代码,我们就能够快速地制作一个简单的XY坐标系了。接下来我们只需要根据实际需要在坐标系上添加数据点、数据线等元素即可。