使用::after伪元素可灵活创建分割线,通过content配合定位与样式实现竖线、渐变线或装饰符号,如.item:not(:last-child)::after添加竖线,.section::after用渐变做柔和分隔,.divider::after插入圆点或Unicode字符装饰,提升视觉效果且无需额外标签。

使用 ::after 伪元素实现分割线装饰,是一种常见且灵活的CSS技巧。它可以在不增加额外HTML标签的情况下,为元素添加视觉上的分隔效果,比如在列表项、导航链接之间插入线条或装饰性图案。
基本原理
::after 伪元素用于在选定元素的内容之后插入生成的内容。通过设置 content 属性(即使为空),结合 display、position 和边框或背景样式,就能创建出各种分割线效果。
常见实现方式:横向分割线
适用于列表项之间添加竖线或横线分隔,以下是一个在行内元素后添加竖线的例子:
.item {
position: relative;
padding-right: 12px;
display: inline;
}
.item::after {
content: "";
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
width: 1px;
height: 12px;
background-color: #ccc;
}
说明:每个 .item 后面生成一条垂直短线,用绝对定位控制位置,避免最后一个元素也显示分割线,可配合 :not(:last-child) 使用:
立即学习“前端免费学习笔记(深入)”;
.item:not(:last-child)::after {
content: "";
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
width: 1px;
height: 12px;
background-color: #ccc;
}
使用边框模拟长分割线
如果想在段落或模块之间添加横贯的分隔线,可以用 ::after 模拟一条带装饰的线:
.section::after {
content: "";
display: block;
width: 80%;
height: 1px;
background: linear-gradient(90deg, transparent, #ddd, transparent);
margin: 10px auto;
}
这里使用渐变背景让线条两端淡出,视觉更柔和。也可以用 border-top 实现基础线:
.separator::after {
content: "";
display: block;
margin: 20px 0;
border-top: 1px dashed #ccc;
}
添加装饰性符号作为分隔
除了纯线条,还可以用字符或图标做装饰分隔,比如中间一个圆点或箭头:
.divider::after {
content: "•";
display: block;
text-align: center;
font-size: 1.2em;
color: #999;
margin: 10px 0;
}
或者使用Unicode符号:
/* 例如:» 或 ──●── */
.decorative::after {
content: " ──●── ";
color: #aaa;
display: block;
text-align: center;
margin: 15px 0;
}
基本上就这些方法,关键是利用 content 触发伪元素,再通过布局和样式控制外观。注意不要给不需要的元素添加多余分割线,合理使用 :not(:last-child) 能提升细节体验。










