css制作斜线
使用 CSS 制作斜线的方法
使用 linear-gradient 背景渐变
通过 CSS 的 linear-gradient 可以创建斜线效果。这种方法适合作为背景或装饰性元素。
.diagonal-line {
width: 100px;
height: 100px;
background: linear-gradient(to bottom right, transparent 49%, black 49%, black 51%, transparent 51%);
}
使用 transform: rotate() 旋转矩形
将一个矩形元素旋转一定角度,形成斜线。可以通过调整 width 和 height 控制斜线的粗细和长度。

.rotated-line {
width: 100px;
height: 2px;
background-color: black;
transform: rotate(45deg);
transform-origin: 0 0;
}
使用伪元素 (::before 或 ::after)
通过伪元素结合 transform 或 border 属性生成斜线,适合在特定元素上添加装饰性斜线。
.element::before {
content: "";
position: absolute;
width: 100px;
height: 1px;
background-color: black;
transform: rotate(30deg);
}
使用 clip-path 裁剪路径
通过 clip-path 裁剪出一个斜线形状的区域,适合复杂斜线或斜线组合。

.clipped-line {
width: 100px;
height: 100px;
background-color: black;
clip-path: polygon(0 0, 100% 100%, 0 100%);
}
使用 SVG 内联
直接在 HTML 中嵌入 SVG 的 <line> 元素,适合需要精确控制斜线起点和终点的情况。
<svg width="100" height="100">
<line x1="0" y1="0" x2="100" y2="100" stroke="black" stroke-width="2" />
</svg>
结合 border 和透明边框
通过设置部分边框为透明,可以模拟斜线效果,适合简单对角线。
.border-line {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-bottom: 50px solid black;
}
注意事项
- 斜线的角度通过
rotate或linear-gradient的方向参数(如to bottom right)调整。 - 斜线的粗细通过调整
height(旋转矩形)或stroke-width(SVG)控制。 - 斜线的颜色和透明度通过
background-color或stroke属性修改。






