css制作标尺
使用CSS制作标尺的方法
方法一:使用线性渐变和伪元素
通过CSS的线性渐变和伪元素可以创建水平或垂直标尺。以下是一个水平标尺的示例代码:
.ruler {
width: 100%;
height: 20px;
background: linear-gradient(to right, #000 1px, transparent 1px) 0 0 / 10px 20px;
position: relative;
}
.ruler::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: linear-gradient(to right, #000 10px, transparent 10px) 0 0 / 100px 20px;
}
方法二:使用边框和绝对定位
这种方法通过边框和绝对定位来创建标尺刻度:
.ruler {
position: relative;
width: 300px;
height: 30px;
border-bottom: 1px solid #000;
}
.ruler span {
position: absolute;
bottom: 0;
width: 1px;
height: 10px;
background: #000;
}
.ruler span:nth-child(5n) {
height: 15px;
}
.ruler span:nth-child(10n) {
height: 20px;
}
方法三:使用Flexbox布局
Flexbox可以方便地创建均匀分布的标尺刻度:
.ruler {
display: flex;
width: 300px;
height: 20px;
border-bottom: 1px solid #000;
}
.ruler div {
flex: 1;
border-right: 1px solid #000;
height: 5px;
}
.ruler div:nth-child(5n) {
height: 10px;
}
.ruler div:nth-child(10n) {
height: 15px;
border-right: 2px solid #000;
}
方法四:使用CSS Grid布局
CSS Grid提供了另一种创建标尺的方式:
.ruler {
display: grid;
grid-template-columns: repeat(10, 1fr);
width: 300px;
height: 20px;
border-bottom: 1px solid #000;
}
.ruler div {
border-right: 1px solid #000;
height: 5px;
}
.ruler div:nth-child(5n) {
height: 10px;
}
.ruler div:nth-child(10n) {
height: 15px;
border-right: 2px solid #000;
}
垂直标尺的实现
将上述方法中的方向属性调整即可创建垂直标尺:
.vertical-ruler {
height: 300px;
width: 20px;
border-right: 1px solid #000;
background: linear-gradient(to bottom, #000 1px, transparent 1px) 0 0 / 20px 10px;
}
添加数字标签
可以通过伪元素或额外元素为标尺添加数字:
.ruler::after {
content: "0 10 20 30 40 50";
position: absolute;
bottom: -20px;
left: 0;
width: 100%;
text-align: center;
font-size: 12px;
}
这些方法提供了灵活的标尺创建方式,可以根据具体需求调整颜色、尺寸和刻度密度。







