核心原理
- 文字內容寫在 HTML
data-content 屬性。
::before 偽元素 content: attr(data-content) 複製文字。
- 偽元素
position: absolute 覆蓋原文字,設定 width / overflow: hidden 只顯示部分。
- 原文字保持完整(可選、可複製、無障礙友善)。
完整實作
.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 防止換行破壞對齊。
- 無障礙:原文字保留,螢幕閱讀器正常讀取;偽元素內容不被讀取(預設)。
- 複製貼上:複製的是原文字,無副本干擾。