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

使用::after伪类实现a标签悬停动画效果异常排查

问题根因
  • 悬停时文字未变白:#hero a:hover, 选择器末尾多了多余的英文逗号,造成该条CSS规则解析失败,无法生效
  • 下划线宽度占满父元素、位置偏移到父元素底部:给下划线伪元素设置了绝对定位,但没有给<a>标签本身设置相对定位,伪元素会默认向上查找最近的带定位属性的祖先元素(也就是#hero区块)作为定位基准,因此宽度、位置都参照父元素计算;同时伪元素上写的left: 20px是多余的偏移值
  • 下划线距离文字过远:因为伪元素参照父元素定位,bottom:0是对齐父元素底部,自然离锚点文字很远
修复方案
  1. 删除#hero a:hover选择器末尾多余的逗号
  2. 给#hero a增加position: relative属性,作为伪元素的定位基准
  3. 调整伪元素的定位属性:删除多余的left: 20px,将left设为0,调整bottom值为-8px(可根据视觉需求微调数值,控制下划线和文字的间距)
修复后完整代码

CSS部分

/* Hero Section */
#hero {
  color: white;
  height: 80vh;
  padding: 0 100px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  flex-direction: column;
  position: relative;
}

#hero h1{
  margin:0;
  font-size: 3.5rem;
  font-weight: 900;
  padding-bottom:3rem;
  width: 40%;
}

#hero p{
  margin:0;
  font-size: 1.5rem;
  font-weight: 400;
  padding-bottom: 1.5rem;
  width: 30%;
}

#hero a{
  text-decoration: none;
  color: #e50914;
  font-size: 2rem;
  font-weight: 700;
  transition: 200ms ease-in-out;
  position: relative;
}

#hero a:hover{
  color:white;
}

#hero a::after{
  content: "";
  width: 0;
  height: 5px;
  background: #e50914;
  position: absolute;
  bottom: -8px;
  left: 0;
  transition: 200ms ease-in-out;
}

#hero a:hover::after{
  width: 100%;
}

.video-gradient{
}

.back-video {
  position: absolute;
  right: 0;
  bottom: 0;
  top: 0px;
  min-width: 100%;
  min-height: 80%;
  width: auto;
  height: auto;
  z-index: -100;
}

HTML部分

<body>
  <section id="header">
    <a href="#"><img src="images/logo.png" class="logo"></a>
    <div>
      <ul id="navbar">
        <li><a class="active" href="why.html">Why Snap Smile</a></li>
        <li><a href="solutions.html">Solutions</a></li>
        <li><a href="pricing.html">Pricing</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href=""><i class="fa-solid fa-headset"></i></a></li>
      </ul>
    </div>
  </section>
  <section id="hero">
    <h1>Get Your Hollywood Smile Today</h1>
    <p>Show off your million dollar smile with your Snap Smile Veneers</p>
    <a href="#">BOOK NOW</a>
  </section>
</body>

可选优化:代码里给下划线加了宽度从0到100%的过渡效果,和原有文字颜色过渡保持一致,交互体验更流畅,如果不需要可以直接删除对应transition属性。另外修复了原有代码里h1标签闭合标签错写为h2的笔误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:06:10