按钮:hover时:after内容显示,移出鼠标后内容下移问题求助
问题:按钮伪元素箭头移出时下移再消失的原因与解决方法
问题描述
我有一个按钮,其:after伪元素中的箭头内容在鼠标悬停时显示,但鼠标移出按钮时,箭头会先瞬间下移再消失。我想知道问题原因,以及如何实现箭头垂直位置全程固定的效果——我试过修改top属性抵消偏移,但怎么调都没用。
问题原因
问题核心在于鼠标悬停时切换了按钮的display属性:
- 默认状态下,按钮是
display: inline-block(button元素默认值),内部文本通过text-align: center居中,:after伪元素作为inline-block与文本基于基线对齐 - 悬停时你给按钮设置了
display: flex,flex容器的垂直对齐规则会改变内部元素的位置,此时伪元素和文本是flex布局下的垂直居中状态 - 鼠标移出时,按钮从
flex切回默认display,伪元素的垂直对齐瞬间变回基线对齐,就出现了下移后消失的视觉bug
解决方案
方法1:取消悬停时的display切换,统一对齐规则
去掉悬停时的display: flex和justify-content: center,给伪元素添加垂直对齐属性,确保和文本始终在同一水平线:
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap'); * { padding: 0; margin: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; font-size: 62.5%; background-color: #4731D3; } #projects-btn { font-size: 1.6rem; width: 200px; background: none; color: #CBF281; border: 1px solid #CBF281; border-radius: 5px; padding: 10px 0px; margin-top: 50px; transition: all 1s; overflow: hidden; text-align: center; } #projects-btn:after { display: inline-block; position: relative; text-rendering: auto; -webkit-font-smoothing: antialiased; font: var(--fa-font-solid); content: "\f178"; color: #CBF281; padding-left: 0px; transition: all 0.5s ease; opacity: 0; vertical-align: middle; /* 新增:与文本垂直居中对齐 */ } #projects-btn:hover { cursor: pointer; /* 删除display:flex和justify-content:center */ } #projects-btn:hover:after { opacity: 1; padding-left: 15px; }
方法2:始终使用flex布局,保持规则统一
直接给按钮默认设置display: flex,全程用flex布局管理内部元素,避免切换布局带来的对齐变化:
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap'); * { padding: 0; margin: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; font-size: 62.5%; background-color: #4731D3; } #projects-btn { font-size: 1.6rem; width: 200px; background: none; color: #CBF281; border: 1px solid #CBF281; border-radius: 5px; padding: 10px 0px; margin-top: 50px; transition: all 1s; overflow: hidden; display: flex; /* 默认设置flex布局 */ justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } #projects-btn:after { display: inline-block; position: relative; text-rendering: auto; -webkit-font-smoothing: antialiased; font: var(--fa-font-solid); content: "\f178"; color: #CBF281; padding-left: 0px; transition: all 0.5s ease; opacity: 0; } #projects-btn:hover { cursor: pointer; } #projects-btn:hover:after { opacity: 1; padding-left: 15px; }
内容的提问来源于stack exchange,提问作者markisawesome4
相关产品推荐
相关产品推荐

