如何使用CSS在progress-container div上方添加居中垂直虚线
解决方案
通过CSS伪元素实现,无需修改原有DOM结构,符合纯CSS实现要求:
/* 原有样式基础上新增/修改以下内容 */ .wrapperDiv { position: relative; /* 若多个条目堆叠,可添加上内边距给虚线预留显示空间,按需调整数值 */ padding-top: 24px; } .progress-container { position: relative; /* 原有样式保持不变 */ height: 22px; width: 22px; margin-right: 16px; background-color: red; display: flex; } /* 生成居中垂直虚线 */ .progress-container::before { content: ""; position: absolute; left: 50%; transform: translateX(-50%); /* 高度占满上方可用空间,数值和wrapperDiv的padding-top保持一致即可 */ top: -24px; bottom: 100%; width: 1px; /* 虚线样式,可自定义颜色、段长、间距 */ background-image: linear-gradient(to bottom, #999 50%, transparent 50%); background-size: 1px 4px; background-repeat: repeat-y; } /* 首个进度节点不需要顶部虚线,添加该样式隐藏 */ .wrapperDiv:first-child .progress-container::before { display: none; } /* 原有其余样式保持不变 */ .input-wrapper { border: 1px solid #ced4da; border-radius: 2px; overflow-y: hidden; padding: 0.375rem 1.75rem 0.375rem 0.75rem; }
<!-- 修正原HTML标签语法错误后的代码 --> <div class="wrapperDiv"> <div class="progress-container"></div> <div class="input-wrapper"> <div class="input">I have my first input here</div> </div> </div> <!-- 多个条目直接重复wrapperDiv结构即可 --> <div class="wrapperDiv"> <div class="progress-container"></div> <div class="input-wrapper"> <div class="input">I have my second input here</div> </div> </div>
效果说明
- 虚线完全居中于
.progress-container顶部,可通过修改background-image的颜色值、background-size的第二个参数调整虚线的视觉效果 - 若需要调整虚线高度,只需同步修改
.wrapperDiv的padding-top值和伪元素的top值即可适配不同布局的可用高度
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

