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

锚点标签hover时背景左滑过渡不显示,仅显示下划线问题求助

问题描述

我希望锚点标签在鼠标悬停(hover)时,呈现从左至右的背景颜色过渡效果,但当前仅能看到下划线动画,背景效果无法显示。使用的CSS代码如下:

.project a {
  font-size: 27px;
  text-decoration: none;
  position: relative;
  color: rgb(190, 190, 190);
  display: inline-block;
  overflow: hidden;
}

.project a::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 3px;
  background-color: #3498db;
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
}

.project a:hover::after {
  transform: scaleX(1);
  transform-origin: left;
}

.project a:hover {
  color: rgb(240, 240, 240);
}

整个文件中没有其他针对锚点标签的CSS样式。尝试过不使用伪元素、使用keyframes来实现动画,但只有伪元素能达到我想要的动画形式,不过现在背景过渡效果无法显示,仅下划线动画生效,希望解决该问题。

解决方案

你当前的伪元素仅设置了3px高度并定位在底部,所以只会显示下划线效果。要实现从左到右的背景填充过渡,只需调整伪元素的定位、尺寸和层级,确保它覆盖整个锚点区域且不遮挡文字:

.project a {
  font-size: 27px;
  text-decoration: none;
  position: relative;
  color: rgb(190, 190, 190);
  display: inline-block;
  overflow: hidden;
  /* 可选:添加内边距,让背景效果更舒展 */
  padding: 4px 0;
}

.project a::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0; /* 改为顶部定位,覆盖元素全高度 */
  width: 100%;
  height: 100%; /* 高度设为100%,实现背景填充 */
  background-color: rgba(52, 152, 219, 0.2); /* 用半透明色避免遮挡文字 */
  transform: scaleX(0);
  transform-origin: left; /* 初始从左侧收起,hover时展开 */
  transition: transform 0.3s ease;
  z-index: -1; /* 将伪元素置于文字下方 */
}

.project a:hover::after {
  transform: scaleX(1);
}

.project a:hover {
  color: rgb(240, 240, 240);
}

核心修改说明:

  • 调整伪元素定位与尺寸:top:0+height:100%让它覆盖整个锚点元素范围
  • 添加z-index: -1:确保背景在文字下方,不遮挡内容
  • 优化背景色:使用半透明rgba值,兼顾动画效果与文字可读性
  • 统一transform原点:保持从左向右的展开逻辑,动画更连贯

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:55:10