You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现鼠标悬停(hover)时主内容移动,同时保持before/after伪元素静止?

没问题,咱们调整下代码就能实现你想要的效果——鼠标悬停时黑色背景留在原地,上面的Support卡片移动。

问题分析

原来的代码逻辑搞反啦:你让伪元素(黑色背景)在hover时移动,而.test本身没设置position,所以hover时的top/left根本不起作用。咱们要把逻辑反过来:让黑色背景固定,.test自己移动。

修改后的代码

<div>
  <div class="test">
    <i class="fas fa-users fa-4x"></i>
    <h3>Support</h3>
    <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto nemo quisquam iste aliquam nam nesciunt tempore consectetur quaerat libero impedit. </p>
  </div>
</div>

<style>
div { 
  width: 60vw; 
  margin: 100px auto; 
  position: relative; 
}
.test { 
  background-color: rgb(202, 129, 27); 
  display: block;
  position: relative; /* 关键:给卡片添加相对定位,让top/left生效 */
  transition: all 0.5s linear; /* 添加过渡动画,让移动更平滑 */
}
.test::before { 
  content: ""; 
  background-color: black; 
  width: 100%; 
  height: 100%; 
  position: absolute; 
  box-sizing: border-box; 
  top: 0px; 
  left: 0px; 
  z-index: -1; 
  /* 这里不需要hover时的位置变化,让背景固定 */
}
.test:hover { 
  top: -20px; /* 鼠标悬停时,卡片向上移动20px */
  left: -20px; /* 向左移动20px,你可以根据需求调整数值 */
}
</style>

关键调整点

  • 给.test加上position: relative,这样它的top/left属性才能生效,实现移动效果。
  • 给.test添加transition过渡动画,让移动过程更流畅自然。
  • 移除伪元素:hover里的top/left修改,让黑色背景保持在初始位置不动。
  • 在.test:hover里设置卡片的偏移值,你可以根据喜好调整top和left的数值,比如改成10px让卡片向右下移动也可以。

内容的提问来源于stack exchange,提问作者Ragazini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 03:02:48