如何使用CSS ::before、::after实现两端带圆点且完全对齐的横线
问题原因
你当前的实现出现对齐问题的核心原因有两点:
- 伪元素默认是行内级元素,采用基线对齐规则,和高度仅3px的父容器无法自然垂直居中
- 父容器没有统一的布局规则控制两个伪元素的水平位置,很容易出现偏移
解决方案
使用Flex布局控制父容器和伪元素的对齐关系,是最简单且兼容性好的实现方式,调整后的代码如下:
修改后的CSS代码
.line { height: 3px; width: 50px; background: green; /* 新增Flex布局相关配置 */ display: flex; align-items: center; justify-content: space-between; } .line::before { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: green; } .line::after { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: green; }
SCSS适配调整
你现有的SCSS代码不需要大幅修改,只要给.line选择器新增Flex相关配置即可:
.line { margin-bottom: 8px; height: 3px; width: 50px; background: green; display: flex; align-items: center; justify-content: space-between; &:before, &:after { @extend .dot; background: green; } } .dot { content: ""; display: inline-flex; width: 10px; height: 10px; border-radius: 50%; }
效果说明
修改后:
- 垂直方向:
align-items: center会让圆点的中心和横线的中心完全重合,实现垂直对齐 - 水平方向:
justify-content: space-between会让两个伪元素分别贴在横线的左右两端,不会出现偏移 - 额外说明:伪元素的content不需要写
\A,空字符串""就可以满足需求
内容的提问来源于stack exchange,提问作者CitizenFiftyTwo
相关产品推荐
相关产品推荐

