【CSS技巧】给按钮添加下划线动画

按钮或菜单项添加 hover 时下划线动画,可以给界面增色不少。

一种巧妙的方式是通过after伪元素来实现(在线示例):

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>HTML + CSS</title>
    <link rel="stylesheet" href="styles.css" />
    <style>
      .c-text-button {
        position: relative;
        display: inline-flex;
        align-items: center;
        padding: 2px 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
      }
      .c-text-button::after {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 0;
        height: 1px;
        background-color: currentcolor;
        content: "";
        transition: width 0.3s ease;
      }
      .c-text-button:hover {
        opacity: 1;
        transform: translateY(-1px);
      }
      .c-text-button:hover::after {
        width: 100%;
      }

    </style>
  </head>
  <body>
    <div class="c-text-button">button</div>
  </body>
</html>
相关推荐
C+++Python7 小时前
如何使用CSS Grid?
css
Henry_Lau6179 小时前
主流IDE常用快捷键对照
前端·css·ide
C+++Python9 小时前
CSS Grid和Flexbox有什么区别?
css
请叫我聪明鸭13 小时前
CSS实现单行、多行文本超长显示 / 不超长隐藏、悬浮窗超长展示/不超长隐藏、悬浮窗手动控制样式
前端·javascript·css
码云之上15 小时前
WEB端小屏切换纯CSS实现
前端·css
苏打水com16 小时前
第十五篇:Day43-45 前端性能优化进阶——从“可用”到“极致”(对标职场“高并发场景优化”需求)
前端·css·vue·html·js
@大迁世界16 小时前
08.CSS if() 函数
前端·css
苏打水com16 小时前
第十六篇:Day46-48 前端安全进阶——从“漏洞防范”到“安全体系”(对标职场“攻防实战”需求)
前端·javascript·css·vue.js·html
2501_9181269120 小时前
用html5写一个国际象棋
前端·javascript·css
小肖爱笑不爱笑20 小时前
2025/12/16 HTML CSS
java·开发语言·css·html·web