中点展开效果需用::before伪元素设content:""、position:absolute、transform:scaleX(0)、transform-origin:center,父容器设position:relative和overflow:hidden;hover时transform:scaleX(1),仅过渡transform以避免重排;文字层需加position:relative和z-index:1防遮挡。
::before 伪元素配合 transform: scaleX(0) 实现中点展开效果核心是把伪元素当作一个“遮罩层”,初始缩为一条竖线(scaleX(0)),再通过 transition 拉伸到全宽。注意必须设 content: ""、position: absolute,且父容器需为 position: relative。
常见错误是忘记给伪元素设 top/left/right/bottom 定位,导致它脱离按钮内容区域;或没限制 overflow: hidden,拉伸时背景溢出边框。
100%,高度与按钮一致(如 height: 100% 或固定值)transform-origin: center 确保从中间开始缩放(默认就是 center,但显式写更稳妥)transition 推荐只过渡 transform,避免触发重排transform: scaleX(1),不能用 width
用 width 动画会触发浏览器重排(reflow),性能差,尤其在移动端容易卡顿;而 transform 只走合成器,GPU 加速,流畅得多。同时 scaleX(1) 天然保持中心对齐,不用额外计算偏移。
典型错误写法:width: 0 → width: 100%,不仅慢,还可能因盒模型变化导致文字微跳。
立即学习“前端免费学习笔记(深入)”;
transform: scaleX(0); transform-origin: center;
transform: scaleX(1);
transition: transform 0.3s ease; 到伪元素上(不是按钮本身)z-index 和层叠上下文伪元素默认渲染在按钮内容上方,文字会被遮挡。解决方案很简单:给按钮文字所在元素(比如 <span> 或直接 <button>)加 position: relative 和 z-index: 1,让文字层高于伪元素(伪元素保持默认 z-index: auto)。
另一个坑是按钮用了 overflow: hidden 却没给伪元素设 border-radius,导致拉伸时圆角失效——此时要把 border-radius 同时加在按钮和伪元素上。
position: relative; overflow: hidden;
border-radius: inherit;(或显式写相同值)position: relative; z-index: 1;
transform 在伪元素上的动画IE11 虽支持 ::before 和 transform,但对伪元素的 transform 过渡支持不完整,动画常卡在起点。如果必须兼容 IE,得降级为 JS 控制 class 切换 + width 动画,或直接放弃该动效。
现代项目可放心用,但要注意 Safari 旧版本(transform-origin 在绝对定位伪元素上的解析有细微偏差,建议统一用 transform-origin: center center 显式声明。
真正难调的不是写法,而是按钮高矮不一、字体行高浮动时,伪元素高度对不齐文字基线——这时候别硬撑,用 top: 50%; transform: translateY(-50%) 垂直居中更稳。