利用 ::before 或 ::after 偽元素複製文字內容,配合 overflow: hidden 和 width 控制顯示範圍,即可實現單一字元的多色、漸變、動態變色效果,且 HTML 保持乾淨無重複文字。
.half-color {
display: inline-block;
position: relative;
font-size: 80px;
line-height: 1;
color: #000; /* 原文字顏色(右半部) */
white-space: nowrap; /* 防換行 */
overflow: hidden; /* 隱藏溢出 */
}
.half-color::before {
content: attr(data-text); /* 從 data-text 屬性取得文字 */
position: absolute;
left: 0; top: 0;
color: #f00; /* 偽元素文字顏色(左半部) */
width: 50%; /* 顯示寬度 50% */
overflow: hidden;
white-space: nowrap;
}
HTML:
<span class="half-color" data-text="Web">Web</span>
.diagonal-color::before {
width: 100%;
background: linear-gradient(45deg, #f00 50%, transparent 50%);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
/* 此法不需 overflow hidden,直接用漸變裁切文字 */
}
.scan-color::before {
content: attr(data-text);
position: absolute;
left: 0; top: 0;
color: #f00;
width: 0;
overflow: hidden;
white-space: nowrap;
animation: scan 2s linear infinite;
}
@keyframes scan {
to { width: 100%; }
}
現代瀏覽器支援 background-clip: text,可直接對文字套用多色漸變,無需偽元素:
.multi-color {
background: linear-gradient(90deg, #f00, #0f0, #00f, #ff0);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
| 屬性 | 作用 |
|---|---|
content: attr(data-text) | 動態從 HTML 屬性獲取文字,避免 CSS 硬編碼 |
overflow: hidden | 裁切偽元素顯示範圍 |
white-space: nowrap | 防止文字換行破壞對齊 |
display: inline-block | 建立定位上下文、允許設定寬高 |
position: absolute | 偽元素疊加在原文字上方 |
data-text 僅供視覺層複製,不影響語意。background-clip: text,確保提供回退色(color: #000)。::before/::after:IE8+(單冒號 : 相容)、全現代瀏覽器。background-clip: text:Chrome 48+、Firefox 52+、Safari 15+、Edge 79+(需 -webkit- 前綴)。attr() 在 content 中:全支援;其他屬性中仍在標準化中。偽元素文字變色技巧,讓排版設計突破單色限制,且保持語意純淨。更多 CSS 文字特效,請關注本站前端視覺專題。