如何在水平/垂直文本的环绕线条末端添加箭头
实现带箭头的水平/垂直文本环绕线条
要同时搞定水平和垂直文本的线条+箭头效果,核心思路是用嵌套伪元素拆分线条和箭头的逻辑,再结合flex布局适配不同方向的对齐需求,避免字符箭头带来的字体兼容问题。
完整实现代码
/* 水平文本样式 */ h1 { display: flex; align-items: center; flex-direction: row; gap: 10px; /* 替代margin,更灵活 */ } /* 左侧线条 */ h1::before { content: ""; flex: 1; border-bottom: 1px solid currentColor; } /* 右侧线条+箭头 */ h1::after { content: ""; display: flex; align-items: center; flex: 1; gap: 5px; } h1::after::before { content: ""; flex: 1; border-bottom: 1px solid currentColor; } h1::after::after { content: ""; /* 绘制向右箭头 */ border: solid currentColor; border-width: 0 2px 2px 0; padding: 3px; transform: rotate(-45deg); } /* 垂直文本样式 */ h2 { display: flex; flex-direction: row; writing-mode: vertical-rl; transform: scale(-1); align-items: center; height: 400px; /* 固定高度方便预览效果 */ gap: 10px; } /* 上方箭头+线条 */ h2::before { content: ""; display: flex; flex-direction: column; justify-content: center; flex: 1; gap: 5px; } h2::before::before { content: ""; /* 适配垂直文本方向的向上箭头 */ border: solid currentColor; border-width: 2px 0 0 2px; padding: 3px; transform: rotate(45deg); } h2::before::after { content: ""; flex: 1; border-right: 1px solid currentColor; } /* 下方线条 */ h2::after { content: ""; flex: 1; border-right: 1px solid currentColor; }
<h1>My horizontal text</h1> <h2>My vertical text</h2>
关键逻辑说明
- 嵌套伪元素:主伪元素作为容器,内部再拆分出线条和箭头两个子伪元素,用flex的
gap控制间距,比margin更易维护。 - 箭头绘制:用border模拟箭头形状,通过
transform: rotate调整方向,颜色继承currentColor,确保和文本、线条颜色统一。 - 垂直适配:针对
writing-mode: vertical-rl和transform: scale(-1)的文本方向,调整箭头旋转角度,保证指向符合预期。 - flex布局:通过
flex:1让线条自动填充剩余空间,同时实现文本与线条的居中对齐,适配水平/垂直两种布局方向。
内容的提问来源于stack exchange,提问作者jph
相关产品推荐
相关产品推荐

