萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 單一字元局部變色技巧:偽元素 :before 搭配 data-* 屬性實現文字漸變、雙色效果

核心原理

  1. 文字內容寫在 HTML data-content 屬性。
  2. ::before 偽元素 content: attr(data-content) 複製文字。
  3. 偽元素 position: absolute 覆蓋原文字,設定 width / overflow: hidden 只顯示部分。
  4. 原文字保持完整(可選、可複製、無障礙友善)。

完整實作

.half-color {
  display: inline-block;
  font-size: 80px;
  line-height: 1;
  color: #000;           /* 原文字顏色(右半/未被覆蓋部分) */
  position: relative;
  overflow: hidden;
  white-space: pre;      /* 保留空白 */
}
.half-color::before {
  content: attr(data-content);
  position: absolute;
  left: 0; top: 0;
  color: #f00;           /* 覆蓋層顏色(左半) */
  width: 50%;            /* 只顯示左半 */
  overflow: hidden;
}
<span class="half-color" data-content="Web">Web</span>
<span class="half-color" data-content="前">前</span>
<span class="half-color" data-content="端">端</span>

擴展應用

  • 漸變文字:background: linear-gradient(...); -webkit-background-clip: text; color: transparent;(現代標準做法)。
  • 多色分段:多層偽元素 ::before、::after、::first-letter 組合。
  • 動畫:@keyframes 動態改變 width 實現打字機、掃光效果。

注意事項

  • 需 position: relative 於宿主,偽元素 absolute 定位。
  • white-space: pre 或 nowrap 防止換行破壞對齊。
  • 無障礙:原文字保留,螢幕閱讀器正常讀取;偽元素內容不被讀取(預設)。
  • 複製貼上:複製的是原文字,無副本干擾。
copyright © 萬盛學電腦網 all rights reserved