如何实现嵌套进度条圆角后方保留底层背景色效果?
实现分段进度条右侧圆角且透出后续颜色的效果
需求:3个不同颜色的分段进度条(红色、绿色、蓝色),仅为每个进度条的右上和右下侧设置圆角,红色进度条加圆角后后方显示绿色,绿色进度条加圆角后后方显示蓝色,效果如下:

原代码的问题在于给所有进度条添加圆角后,后面的进度条被前面的完全覆盖,无法透出颜色。以下是修正后的实现方案:
完整代码
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <div class="progress custom-progress" style="width: 35%; height: 10px"> <div class="progress-bar" style="width: 20%; background-color: #dc3545"></div> <div class="progress-bar" style="width: 35%; background-color: #28a745"></div> <div class="progress-bar" style="width: 45%; background-color: #4d7a90"></div> </div>
CSS
.custom-progress { display: flex; overflow: visible; /* 允许圆角超出容器,避免被裁剪 */ box-shadow: 0px -4px 4px -2px rgba(0, 0, 0, 0.25) inset, 0px 3px 2.8px 0px rgba(255, 255, 255, 0.8) inset; } .custom-progress .progress-bar { border-top-right-radius: 10px; border-bottom-right-radius: 10px; flex-shrink: 0; /* 保持设置的宽度比例,不被压缩 */ } /* 前两个进度条设置负margin,让后续进度条前移,透出下一段颜色 */ .custom-progress .progress-bar:nth-child(1), .custom-progress .progress-bar:nth-child(2) { margin-right: -10px; /* 值与圆角半径一致,刚好覆盖直角部分,露出圆角弧形区域 */ }
关键调整说明
- 布局改为Flex:使用
display: flex确保进度条稳定横向排列,替代Bootstrap默认的浮动布局; - 取消容器溢出隐藏:去掉
overflow: hidden,避免圆角被容器裁剪; - 负Margin偏移:给前两个进度条设置等于圆角半径的负
margin-right,让后面的进度条向前偏移,覆盖前面进度条的直角部分,而圆角的弧形区域会自然透出后面的颜色; - 固定宽度比例:添加
flex-shrink: 0防止进度条宽度被压缩,保证设置的比例生效。
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

