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

如何用Tailwind CSS实现链接hover时背景色从下至上覆盖效果?

用Tailwind CSS复现文本链接hover时的背景展开效果

要复现你提到的Evan You网站上的链接hover效果,我们需要结合Tailwind工具类和少量自定义CSS(Tailwind原生不支持伪元素如::after的内联配置)。以下是两种可行方案:

方案一:使用自定义CSS片段(无需修改Tailwind配置)

直接定义包含伪元素样式的自定义类,并用@apply复用Tailwind工具类:

/* 自定义CSS */
.link-hover-bg {
  @apply relative no-underline whitespace-nowrap text-[#121314];
}

.link-hover-bg::after {
  content: '';
  @apply absolute z-[-1] top-[66%] left-[-0.1em] right-[-0.1em] bottom-0 transition-top duration-200 [transition-timing-function:cubic-bezier(0,0.8,0.13,1)] bg-[rgba(79,192,141,0.5)];
}

.link-hover-bg:hover::after {
  @apply top-0;
}

对应的HTML使用方式:

<p class="text-[#121314]">hello, <a href="#" class="link-hover-bg">Jack</a></p>

方案二:通过Tailwind配置添加自定义工具类

若希望将效果封装为Tailwind工具类,可修改tailwind.config.js:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [
    function({ addUtilities }) {
      addUtilities({
        '.link-hover-bg': {
          position: 'relative',
          textDecoration: 'none',
          whiteSpace: 'nowrap',
          color: '#121314',
        },
        '.link-hover-bg::after': {
          content: '""',
          position: 'absolute',
          zIndex: '-1',
          top: '66%',
          left: '-0.1em',
          right: '-0.1em',
          bottom: '0',
          transition: 'top 200ms cubic-bezier(0, 0.8, 0.13, 1)',
          backgroundColor: 'rgba(79, 192, 141, 0.5)',
        },
        '.link-hover-bg:hover::after': {
          top: '0%',
        },
      })
    }
  ],
}

之后在HTML中直接使用.link-hover-bg类即可,写法与方案一一致。

效果说明

  • 链接默认无下划线、文本不换行,颜色为#121314
  • 伪元素作为背景层初始覆盖文本下半部分(top:66%)
  • hover时伪元素top值变为0,通过自定义缓动函数实现平滑向上展开动画
  • 背景色为半透明绿色(rgba(79,192,141,0.5)),可按需调整颜色或透明度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:05:34