js 横线 实现
使用 CSS border 属性实现横线
在 HTML 中创建一个 div 元素,通过 CSS 的 border 属性设置横线样式。可以调整宽度、颜色和样式来满足不同需求。
<div class="horizontal-line"></div>
.horizontal-line {
border-top: 1px solid #000;
width: 100%;
margin: 10px 0;
}
使用 hr 标签实现横线
HTML 原生提供了 hr 标签用于创建水平分割线,可以通过 CSS 进一步自定义样式。
<hr class="custom-hr">
.custom-hr {
border: 0;
height: 1px;
background-color: #333;
margin: 20px 0;
}
使用伪元素实现横线
通过 ::before 或 ::after 伪元素创建横线,适合在文本前后添加装饰线。
<div class="text-with-line">标题</div>
.text-with-line {
position: relative;
text-align: center;
}
.text-with-line::before {
content: "";
position: absolute;
top: 50%;
left: 0;
right: 0;
border-top: 1px solid #ccc;
z-index: -1;
}
.text-with-line span {
background: white;
padding: 0 10px;
}
使用 SVG 实现横线
SVG 可以实现更复杂的横线效果,如渐变、虚线等。
<svg width="100%" height="1">
<line x1="0" y1="0" x2="100%" y2="0" stroke="#000" stroke-width="1" />
</svg>
使用 Canvas 绘制横线
JavaScript 动态绘制横线,适合需要交互的场景。
<canvas id="lineCanvas" width="200" height="1"></canvas>
const canvas = document.getElementById('lineCanvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, 0.5);
ctx.lineTo(canvas.width, 0.5);
ctx.stroke();
使用 Flexbox 实现文本两侧横线
创建文字两侧带有横线的效果,常用于标题装饰。
<div class="flex-line">
<span class="line"></span>
<span class="text">标题</span>
<span class="line"></span>
</div>
.flex-line {
display: flex;
align-items: center;
}
.line {
flex: 1;
height: 1px;
background-color: #000;
}
.text {
padding: 0 10px;
}





