按钮从下到上的Hover过渡效果未生效,求问题原因
问题原因与解决方案
让我来帮你排查这个按钮hover过渡失效的问题,核心原因和解决办法如下:
主要问题:<input>是替换元素,不支持伪元素
你试图用input[type="submit"]:after实现背景从下到上的过渡效果,但**<input>属于替换元素**(浏览器会根据元素类型渲染内置UI组件,类似的还有<img>、<select>),这类元素的特性决定了它们无法生成:before或:after伪元素。浏览器直接忽略了你的input:after样式,自然看不到背景过渡效果。
另外还有两个小细节需要注意:
- 你写了两个重复的
input[type="submit"]:hover规则,后面的样式会覆盖前面的,虽然这不是过渡失效的主因,但建议合并成一个规则,避免代码冗余。 .hs-button类里定义了position: relative,但伪元素绑定在input上,即使input支持伪元素,这里的定位逻辑没问题,但因为input本身不支持伪元素,所以这条样式也发挥不了作用。
解决方案:两种可行的修复方式
方式一:改用<button>元素(推荐)
<button>是非替换元素,完全支持伪元素,只需要把<input>换成<button>,再调整CSS选择器即可:
修改后的HTML
<div class="hs_submit"> <div class="actions"> <button type="submit" class="hs-button primary large">DOWNLOAD NOW!</button> </div> </div>
调整后的CSS
.hs-button { font-size: 16px; font-family: "Raleway", sans-serif; text-transform: uppercase; line-height: 1em; color: #333333; letter-spacing: 0; background: #fff336; display: inline-block; position: relative; cursor: pointer; border: none; /* 移除button默认边框 */ padding: 12px 24px; /* 添加合适内边距,让按钮更美观 */ -webkit-transition: color 0.3s ease-out; transition: color 0.3s ease-out; } /* 合并hover规则,避免重复 */ .hs-button:hover { color: #fff336; } .hs-button:after { content: ""; background: #000; position: absolute; bottom: 0; left: 0; width: 100%; height: 0; z-index: -1; /* 让伪元素在文字下方 */ -webkit-transition: height 0.3s ease-out; transition: height 0.3s ease-out; } .hs-button:hover:after { height: 100%; }
方式二:用容器包裹<input>,借助容器的伪元素实现
如果一定要保留<input>元素,可以给它套一个容器,用容器的伪元素来做背景过渡:
修改后的HTML
<div class="hs_submit"> <div class="actions"> <div class="button-wrap"> <input type="submit" value="DOWNLOAD NOW!" class="hs-button primary large"> </div> </div> </div>
调整后的CSS
.button-wrap { display: inline-block; position: relative; z-index: 1; } .hs-button { font-size: 16px; font-family: "Raleway", sans-serif; text-transform: uppercase; line-height: 1em; color: #333333; letter-spacing: 0; background: transparent; /* 把按钮背景设为透明,让容器伪元素显示 */ display: inline-block; cursor: pointer; border: none; padding: 12px 24px; position: relative; z-index: 2; /* 确保文字在背景上方 */ -webkit-transition: color 0.3s ease-out; transition: color 0.3s ease-out; } .button-wrap:after { content: ""; background: #000; position: absolute; bottom: 0; left: 0; width: 100%; height: 0; z-index: 1; -webkit-transition: height 0.3s ease-out; transition: height 0.3s ease-out; } .button-wrap:hover:after { height: 100%; } .button-wrap:hover .hs-button { color: #fff336; }
内容的提问来源于stack exchange,提问作者Freddy
相关产品推荐
相关产品推荐

