CSS实现Hover时拆分边框转完整边框:无法拆分边框求助
需求与问题描述
我想要实现这样的边框交互效果:
- 初始状态:上下边框为分段样式(上边框左侧一段、下边框右侧一段,类似方括号
[ ]的视觉效果),左右边框保持完整显示 - 鼠标悬停(hover)时:上下边框平滑过渡为完整宽度,形成闭合的矩形边框
- 悬停结束后:自动恢复到初始的分段边框状态
目前无法正确实现上述边框拆分及过渡效果,以下是我当前的代码:
当前HTML代码
<div class="container-fluid about_us py-5 ms-5 mt-5"> <div class="row"> <!-- Left: Counter Section --> <div class="col-md-4 left d-flex align-items-center"> <div class="counter d-flex align-items-center"> <div class="counter-number-wrapper"> <span class="counter-number ps-5">25</span> </div> <div class="counter-title-wrap text-end pe-3"> <div class="counter-title"> <span>Years</span> <span>experience</span> <span>working</span> </div> </div> </div> </div> </div>
当前CSS代码
.counter { position: relative; padding: 30px 30px 25px 38px; display: flex; align-items: center; border-left: 10px solid #393c42; /* Solid left border */ border-right: 10px solid #393c42; /* Solid right border */ border-radius: 0; /* No rounded corners initially */ transition: all 0.3s ease; } .counter:before, .counter:after { content: ""; position: absolute; width: 40%; /* Length of the border segment */ height: 10px; /* Thickness of the border */ background-color: #393c42; top: 0; /* For the top border */ left: 0; /* For the left part of the top border */ transition: all 0.3s ease; } .counter:after { top: auto; /* Remove the top positioning for bottom */ bottom: 0; /* For the bottom border */ left: auto; /* Remove left positioning */ right: 0; /* For the right part of the bottom border */ } .counter:hover:before, .counter:hover:after { width: 100%; /* Expand borders to full width */ left: 0; /* Reset for full-width hover */ right: 0; }
修复方案
问题出在悬停状态的样式设置上:原代码同时给before和after设置了left:0和right:0,导致下边框分段的位置发生跳跃,破坏了过渡动画的流畅性。
修正后的CSS代码如下,仅调整悬停状态的样式逻辑,保持初始分段的对齐方式,实现平滑扩展:
.counter { position: relative; padding: 30px 30px 25px 38px; display: flex; align-items: center; border-left: 10px solid #393c42; border-right: 10px solid #393c42; border-radius: 0; transition: all 0.3s ease; } .counter:before, .counter:after { content: ""; position: absolute; height: 10px; background-color: #393c42; transition: all 0.3s ease; } /* 上边框左侧分段 */ .counter:before { width: 40%; top: 0; left: 0; } /* 下边框右侧分段 */ .counter:after { width: 40%; bottom: 0; right: 0; } /* 悬停时扩展上边框至全屏(保持左对齐) */ .counter:hover:before { width: 100%; } /* 悬停时扩展下边框至全屏(保持右对齐) */ .counter:hover:after { width: 100%; }
修复说明
- 拆分
before(上边框)和after(下边框)的样式定义,让代码结构更清晰 - 悬停状态仅修改宽度属性,保留初始的对齐方式(上边框左对齐、下边框右对齐),确保过渡动画是平滑的扩展效果,而非位置跳跃
- 保持左右边框的完整显示,与上下分段边框形成初始的方括号视觉效果
内容的提问来源于stack exchange,提问作者Karthick
相关产品推荐
相关产品推荐

