如何实现与步骤数无关的带圆角简化Stepper组件(HTML/CSS)
简化Stepper组件实现方案
我用以下代码实现了Stepper组件,但实现过于复杂,希望简化代码(比如不使用::before伪选择器,仅用一个轮廓元素),同时必须保证组件角度与步骤数量无关,圆角效果是核心要求。
优化思路
- 合并轮廓层级:用
box-shadow模拟描边效果,替代原来的outer-outline和inner-outline两个嵌套元素,无需伪元素就能实现边框+填充的视觉效果 - 保持角度独立性:保留基于CSS变量
--stepper-depth的clip-path多边形路径,箭头角度完全由该变量控制,与步骤总数无关 - 复用圆角滤镜:继续使用SVG的
goo滤镜实现圆角,这是给clip-path生成的自定义形状添加圆角的可靠方案 - 精简DOM结构:每个步骤只保留一个形状容器和内容容器,去掉冗余的嵌套div
优化后的代码
CSS
.stepper { --stepper-height: 75px; --stepper-stroke: 1px; --stepper-depth: 1.5rem; /* 控制箭头角度的深度 */ width: 100%; height: var(--stepper-height); display: flex; margin-right: var(--stepper-depth); } .stepper-step { position: relative; flex: 1 1 0%; height: 100%; /* 核心多边形路径,角度由--stepper-depth控制 */ clip-path: polygon(0% 0%, calc(100% - var(--stepper-depth)) 0%, 100% 50%, calc(100% - var(--stepper-depth)) 100%, 0% 100%, var(--stepper-depth) 50%); /* box-shadow实现描边+填充:内层inset阴影是填充色,外层阴影是边框 */ box-shadow: inset 0 0 0 calc(var(--stepper-height) - var(--stepper-stroke)) white, 0 0 0 var(--stepper-stroke) gray; filter: url(#round); } /* 激活状态样式示例 */ .stepper-step.active { box-shadow: inset 0 0 0 calc(var(--stepper-height) - var(--stepper-stroke)) #eff6ff, 0 0 0 var(--stepper-stroke) #60a5fa; } .stepper-step .content { position: absolute; top: 0; left: var(--stepper-depth); width: calc(100% - var(--stepper-depth) * 2); height: 100%; display: grid; align-content: center; padding-left: 1rem; } .title, .description { margin: 0; }
HTML
<div class="stepper mt-12 px-10"> <div class="stepper-step"> <div class="content"> <p class="title">Step 1</p> <p class="description">description....</p> </div> </div> <div class="stepper-step active"> <div class="content"> <p class="title">Step 2</p> <p class="description">description....</p> </div> </div> <div class="stepper-step"> <div class="content"> <p class="title">Step 3</p> <p class="description">description....</p> </div> </div> </div> <!-- 圆角滤镜,调整stdDeviation可控制圆角大小 --> <svg style="visibility: hidden; position: absolute;" width="0" height="0" xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <filter id="round"> <feGaussianBlur in="SourceGraphic" stdDeviation="4" result="blur" /> <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9" result="goo" /> <feComposite in="SourceGraphic" in2="goo" operator="atop" /> </filter> </defs> </svg>
关键细节说明
- box-shadow双轮廓原理:内层
inset阴影设置为容器高度减去边框宽度,刚好填充整个形状区域;外层阴影设置为边框宽度,模拟描边效果 - 角度可控性:修改
--stepper-depth变量即可调整箭头的尖锐程度,步骤数量变化时不需要修改路径代码 - 圆角滤镜适配:SVG滤镜的
stdDeviation参数对应圆角大小,可根据需求调整,确保自定义形状的边角圆润
内容的提问来源于stack exchange,提问作者Luis Chan
相关产品推荐
相关产品推荐

