利用 ::before / ::after 偽元素複製文字內容,配合 width / overflow: hidden 只顯示部分,再疊加在原文字上方,形成「單字多色」視覺效果。
<span class="hf" data-content="文字">文字</span>
data-content:供偽元素 content: attr(data-content) 讀取,避免內容重複維護。.hf {
display: inline-block;
font-size: 80px;
line-height: 1;
color: #000; /* 原色:顯示右半/下半 */
position: relative;
overflow: hidden;
white-space: pre; /* 保留空白 */
}
.hf::before {
content: attr(data-content);
position: absolute;
left: 0; top: 0;
color: #f00; /* 變色部分 */
width: 50%; /* 顯示左半;改 30% 只變色 30% */
overflow: hidden;
white-space: pre;
}
.hf-v::before {
height: 50%; /* 只顯示上半 */
width: 100%;
overflow: hidden;
}
.hf-diagonal::before {
background: linear-gradient(45deg, #f00 50%, transparent 50%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
width: 100%; height: 100%;
}
@keyframes sweep {
0% { width: 0; }
100% { width: 100%; }
}
.hf-animate::before {
animation: sweep 2s linear infinite;
}
aria-hidden="true" 於偽元素容器,或改用 background-clip: text 純 CSS 方案(支援度較新)。inline-block 容器不換行;長文需改用區塊級容器並處理換行邏輯。font-display: swap 或等待 document.fonts.ready。left: 0 需改為邏輯屬性 inline-start: 0。background-clip: text.gradient-text {
background: linear-gradient(90deg, #f00, #0f0, #00f);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
優點:單一元素、無偽元素、支援漸變、無重複讀取問題。缺點:IE 不支援、無法做「精確百分比切割」(需配合 mask)。
偽元素 ::before + attr() + overflow: hidden 是兼容性最好、控制最精確的「單字局部變色」方案。配合 data-* 屬性實現內容單一來源,再輔以動畫、漸變、遮罩,可創造豐富標題視覺效果。