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

动画元素层级问题:.rocket::before无法显示在.rocket后方

卡片悬停动画问题排查与修复

问题背景

需求:

  • 鼠标悬停卡片时,从下往上填充指定颜色(已实现)
  • 卡片悬停时显示火箭升空动画

当前遇到的问题:.rocket::before 伪元素无法显示在 .rocket 元素的后方

错误原因

.rocket 是定位元素(position: absolute),默认会创建独立的堆叠上下文。此时伪元素设置的 z-index: -1 仅在 .rocket 的堆叠上下文内生效,会被 .rocket 自身的黑色背景遮挡,无法显示在火箭主体后方。

修复方案

  1. 给 .rocket 设置明确的 z-index 值,让伪元素的 z-index: -1 能正确落到火箭主体下方
  2. 替换 display: none 为 opacity + visibility 控制火箭显示,优化动画过渡的流畅感(可选)

修改后的代码如下:

CSS 代码

.main-nav-card {
  background: linear-gradient(
    to bottom,
    transparent 50%,
    #1c7ed6 50%
  );
  background-size: 100% 200%;
  height: 70rem;
  border: 1px solid currentColor;
  padding: 4.8rem 9.6rem;
  border-radius: var(--border-radius-large);
  position: relative;
  z-index: 2;
}

.main-nav-card:hover {
  animation-name: fillCard;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

@keyframes fillCard {
  from {
    background-position: top;
  }

  to {
    background-position: bottom;
  }
}

.rocket {
  /* 替换display:none,优化显示过渡 */
  opacity: 0;
  visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: #000;
  height: 50px;
  width: 25px;
  border-radius: 50% 50% 0 0;
  /* 设置明确z-index,让伪元素层级生效 */
  z-index: 1;
  transition: opacity 0.2s ease;
}

.rocket::before {
  content: "";
  position: absolute;
  bottom: 0;
  right: -15px;
  height: 20px;
  width: 55px;
  border-radius: 50% 50% 0 0;
  background-color: #f03e3e;
  z-index: -1;
}

.rocket::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
  bottom: -4px;
  height: 4px;
  width: 15px;
  border-radius: 0 0 2px 2px;
  background-color: #f03e3e;
  z-index: -1;
}

.main-nav-card:hover .rocket {
  opacity: 1;
  visibility: visible;
  animation-name: flyRocket;
  animation-duration: 3s;
}

@keyframes flyRocket {
  from {
    transform: translateY(1000%);
  }

  to {
    transform: translateY(0);
  }
}

.card-title {
  font-size: 3.2rem;
}

.window {
  height: 10px;
  width: 10px;
  background-color: var(--color-primary);
  border-radius: 50%;
  position: relative;
  top: 17px;
  left: 7.5px;
}

HTML 代码(无需修改)

<div class="main-nav-card">
  <p class="card-title">Introduction</p>

  <div class="rocket">
    <div class="window"></div>
  </div>
</div>

额外说明

  • 给.rocket设置z-index:1后,伪元素的z-index:-1会被放置在火箭主体下方,即可正常显示
  • 用opacity和visibility替代display:none,能让火箭的显示/隐藏有平滑过渡,避免动画突然启动的生硬感

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:34:54