CSS随意练习 -- 文本颜色从中心向两头扩散效果

109 阅读1分钟

前言

  • 为了提升自己的CSS技术,时不时会自己做一些小练习
  • 有时候遇到一些自我感觉有趣的想法,就打算分享并记录下来,说不定哪天实际项目中会遇到,也能参考参考
  • (若以下代码中有啥问题,欢迎友好评论)

需求描述:

    • 1 - 整段文本的字体默认颜色为蓝色
    • 2 - 当鼠标悬浮上去后,会发生一定变化,变化细节如下
      • (2.1 - 整段文本的字体颜色会从中心向两头慢慢扩散发生变色,变成橙色,直到所有文字都改变
      • (2.2 - 文本下方会出现一条下划线,下划线也是从中心向两头慢慢延长,直到跟文本内容一样宽

效果图

Screen-Recording-2024-02-20-at-15.19.39-2.gif

完整源码在此!!!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Text Color Gradient on Hover</title>
  <style>
    body {
      padding: 0;
      margin: 0;
      background-color: black;
    }
    .board {
      /* border: 1px dashed red; */
      height: 36px;
      display: inline-flex;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, 50%);
      overflow: hidden;
    }
    .text-cotainer {
      --var-overtext-color: rgb(255, 162, 0);
      --var-duration: 0.5s;
      position: relative;
      top: -28px;
      width: auto;
      display: inline-flex;
      flex-direction: column;
      align-items: center;
    }
    .text {
      color: blue;
      margin-top: 0;
      margin-bottom: 8px;
    }

    .text-cover-box {
      /* border: 1px dashed gray; */
      flex-shrink: 0;
      width: 0px;
      height: 28px;
      /* border-left: 1px solid var(--var-overtext-color);
      border-right: 1px solid var(--var-overtext-color); */
      display: flex;
      justify-content: center;
      overflow: hidden;
      transition: all var(--var-duration) linear;
      position: relative;
      top: 28px;
    }
    .text-cover-box .text-cover {
      color: var(--var-overtext-color);
      white-space: nowrap;
      height: 28px;
    }

    .text-cotainer:hover .text-cover-box {
      width: 100%;
      height: 28px;
    }

    .text-underline {
      width: 0;
      height: 0;
      border-bottom: 1px solid var(--var-overtext-color);
      transition: all var(--var-duration) linear;
      position: relative;
      top: -5px;
    }

    .text-cotainer:hover .text-underline {
      width: 100%;
    }
  </style>
</head>
<body>
  <div class="board">
    <div class="text-cotainer">
      <div class="text-cover-box"><h2 class="text text-cover">CSS ONly One Let's Go Palworld</h2></div>
      <h2 class="text">CSS ONly One Let's Go Palworld</h2>
      <div class="text-underline"></div>
    </div>
  </div>

  <!-- <div>CSS ONly One Let's Go Palworld</div> -->
</body>
</html>