Skip to content

按钮或菜单项添加 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>