利用 ::before 或 ::after 複製文字內容,配合 width / clip-path / background-clip 只顯示部分區域,疊加在原文字上方,形成「單字多色」視覺效果。
<span class="half-color" data-char="A">A</span>
.half-color {
position: relative;
display: inline-block;
font-size: 48px;
color: #333; /* 底色:深灰 */
overflow: hidden;
white-space: nowrap;
}
.half-color::before {
content: attr(data-char); /* 從 data 屬性獲取文字 */
position: absolute;
left: 0; top: 0;
color: #e74c3c; /* 覆蓋色:紅色 */
width: 30%; /* 只顯示左側 30% */
overflow: hidden;
white-space: nowrap;
}
優點:純 CSS、無 JS、單字可控。
缺點:需在 HTML 重複文字(或用 attr()),多字符需逐字拆分。
.gradient-text {
background: linear-gradient(90deg, #e74c3c, #3498db, #2ecc71);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent; /* fallback */
font-size: 3rem;
font-weight: bold;
}
支援:現代瀏覽器全支援(需 -webkit- 前綴)。這是目前**最推薦**的多色文字方案。
<span class="progress-text" style="--progress: 0%" data-text="Loading...">Loading...</span>
.progress-text {
position: relative;
display: inline-block;
color: #95a5a6; /* 未完成顏色 */
font-size: 24px;
white-space: nowrap;
}
.progress-text::before {
content: attr(data-text);
position: absolute;
left: 0; top: 0;
color: #3498db; /* 完成顏色 */
width: var(--progress, 0%);
overflow: hidden;
white-space: nowrap;
transition: width 0.3s ease;
}
/* JS 更新進度 */
const el = document.querySelector('.progress-text');
let p = 0;
const timer = setInterval(() => {
p += 10;
el.style.setProperty('--progress', `${p}%`);
if (p >= 100) clearInterval(timer);
}, 300);
.clip-text {
position: relative;
color: #333;
font-size: 60px;
font-weight: 800;
}
.clip-text::before {
content: attr(data-text);
position: absolute;
inset: 0;
color: #e74c3c;
clip-path: polygon(0 0, 50% 0, 50% 100%, 0 100%); /* 左半邊 */
/* 或動畫化 */
animation: reveal 2s ease forwards;
}
@keyframes reveal {
from { clip-path: polygon(0 0, 0 0, 0 100%, 0 100%); }
to { clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); }
}
<span class="word-split">
<span data-char="H">H</span>
<span data-char="e">e</span>
<span data-char="l">l</span>
<span data-char="l">l</span>
<span data-char="o">o</span>
</span>
配合 :nth-child() 實現逐字動畫。
function splitText(el, className = 'char') {
const text = el.textContent;
el.innerHTML = [...text].map(c =>
`${c}`
).join('');
}
// 使用
splitText(document.querySelector('.split-me'));
content 屬性必須設置(哪怕空字串 "")才會生成display: inline,常需改為 block 或 inline-block:hover 等偽類直接作用於偽元素(需父級觸發)data-* 屬性複製文字時,螢幕閱讀器可能讀出重複內容aria-hidden="true" 隱藏偽元素內容:<span class="half-color" data-char="A" aria-hidden="true">A</span>background-clip: text)無此問題,最友好| 需求 | 推薦方案 | 關鍵技術 |
|---|---|---|
| 單字固定比例雙色 | 偽元素 + width/overflow | ::before, attr(), overflow:hidden |
| 漸變/多色流暢過渡 | background-clip: text | linear-gradient, -webkit-background-clip |
| 動態進度/載入效果 | 偽元素 + CSS 變數 + JS | --progress, width transition |
| 任意形狀/動畫裁切 | clip-path | polygon(), animation |
| 多字符逐字動畫 | JS 拆分 span + CSS 動畫 | :nth-child, animation-delay |
現代專案首選 background-clip: text 處理漸變文字,特殊裁切需求用 clip-path,動態進度用 CSS 變數驅動偽元素。理解偽元素特性與無障礙影響,才能寫出優雅健壯的代碼。