CSS悬停过渡时保持内容位置不变的问题排查
解决CSS悬停时文本Y轴位置偏移问题
你尝试用top: calc(top - 0.093vw)无效的核心原因有两个:
- CSS的
calc()函数无法直接引用元素自身的当前属性值(比如这里的top),这种写法不被支持; .MBRAnim类本身没有定义初始top值,只有父级类.Map81设置了top: 88.3%,hover时的top计算没有合法的基准值。
另外你在.MBRAnim:hover里重复写了transition: 1s,会导致样式覆盖,而且.Map81的transition-property: top没有作用在hover的过渡逻辑上。
最优解决方案:用transform: translateY()抵消位移
transform不会改变元素的布局空间,性能更优,能精准控制文本位置。修改后的代码如下:
.Container{ /* Container for Map Elements */ position: relative; width: 100%; height: 100%; font-size: 0.45vw; font-family: "p22-underground", sans-serif; font-weight: 600; font-style: normal; } /* 把过渡效果放在基础类,悬停和恢复状态都能平滑过渡 */ .MBRAnim { transition: all 1s ease; } .MBRAnim:hover{ /* Hover animation for Bus Routes in Map Key */ justify-content: center; cursor: pointer; color: white; background-color: white; padding-top: 0.1815vh; padding-bottom: 0.1815vh; /* 向上偏移抵消padding增加带来的文本下移 */ transform: translateY(-0.1815vh); } a:link{ color: black; } a:visited{ color: black; } .Map81{ background-color: #997f53; position: absolute; top: 88.3%; left: 4.4%; }
原理说明
你给元素上下各加了0.1815vh的padding,元素整体高度增加后,文本会自然向下偏移0.1815vh。用transform: translateY(-0.1815vh)让元素整体向上移动相同距离,就能让文本保持在原来的Y轴位置。
备选方案:用负margin抵消
如果不想用transform,也可以用负margin-top实现同样效果:
.MBRAnim:hover{ /* 其他样式不变 */ padding-top: 0.1815vh; padding-bottom: 0.1815vh; margin-top: -0.1815vh; }
内容的提问来源于stack exchange,提问作者Spiritt
相关产品推荐
相关产品推荐

