css 制作虚线
使用 border-style 属性
在 CSS 中,border-style 属性可以设置为 dashed 来创建虚线边框。这是最简单的方法,适用于边框或分割线。
.dashed-border {
border: 2px dashed #000;
}
自定义虚线样式
如果需要更灵活的虚线样式(如调整间隔或线段长度),可以使用 background 和 linear-gradient 模拟虚线效果。
.custom-dashed-line {
height: 2px;
background: linear-gradient(
to right,
#000 50%,
transparent 50%
);
background-size: 10px 2px;
}
background-size: 10px 2px控制虚线的重复周期(10px 为一个线段+间隔的单元)。- 调整
50%的比例可以改变虚线和间隔的比例。
使用 SVG 作为背景
SVG 可以精确控制虚线的样式,适合复杂需求(如斜线虚线)。
.svg-dashed {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='2'%3E%3Cpath d='M0 1h5' stroke='%23000' stroke-width='2' stroke-dasharray='5,3'/%3E%3C/svg%3E");
height: 2px;
}
stroke-dasharray='5,3'表示线段长 5px,间隔 3px。- 修改
width和height可调整 SVG 画布大小。
伪元素实现虚线
通过 ::before 或 ::after 伪元素生成虚线,避免影响原有布局。
.element::after {
content: "";
display: block;
border-top: 2px dashed #000;
margin-top: 10px;
}
文本装饰线
为文本添加虚线装饰时,可使用 text-decoration 属性。
.dashed-underline {
text-decoration: underline dashed;
}






