利用 ::before / ::after 偽元素重疊相同文字,透過 width + overflow:hidden 只露出部分,配合 content: attr(data-content) 動態取得內容,達成「單一字元局部變色」效果,且 HTML 結構保持乾淨。
<span class="hf" data-content="文字">文字</span>
.hf {
display: inline-block;
font-size: 80px;
line-height: 80px;
color: #000; /* 原色 */
position: relative;
overflow: hidden;
white-space: pre; /* 保留空白 */
}
.hf::before {
content: attr(data-content); /* 取得相同文字 */
position: absolute;
left: 0; top: 0;
color: #f00; /* 變色色 */
width: 30%; /* 50% 即半字變色 */
overflow: hidden;
display: block;
}
position:relative 於父層,::before 絕對定位回原位,形成完美重疊。width: 30% 控制變色比例;若需動態比例,可改用 JS 計算寫入 style="--p:30%" 搭配 width: var(--p)。white-space: pre 避免空白折疊導致對齊偏移。::before 改為 background: linear-gradient(...) + -webkit-background-clip: text (現代瀏覽器支援度更好)。@keyframes 動態改變 width 做進度條式讀字效果。IE8+、所有現代瀏覽器完整支援。IE6/7 不支援偽元素,可用 expression 兼容或優雅降級。