利用 CSS clip 屬性,我們能在不使用圖片、不增加 HTML 結構的前提下,實現文字上下半部呈現不同顏色的視覺效果。核心原理:疊放兩組相同內容、不同顏色的文字,透過 clip 裁切各自可見區域,形成雙色文字。

文字上半部:

文字下半部:

兩組文字重疊效果:
clip: auto | rect(top, right, bottom, left)
auto:預設,不裁切rect():依據 上、右、下、左 順序,以元素左上角 (0,0) 為基準點,指定四個偏移值。任一值可用 auto 表示該邊不裁切關鍵限制:必須將元素 position: absolute,clip 才會生效。
<div class="text-container">
<div class="textBottom">Cascading Style Sheet</div>
<div class="textTop">Cascading Style Sheet</div>
</div>
.textBottom {
color: #333333; /* 深灰色:下半部顏色 */
position: absolute;
left: 3em;
top: 1em;
font: 26px 'Century Gothic', Arial, Helvetica, sans-serif;
clip: rect(18px, auto, auto, auto); /* 裁切:保留上方 18px 以下區域(即下半部) */
}
.textTop {
color: #CC0000; /* 紅色:上半部顏色 */
position: absolute;
left: 3em;
top: 1em;
font: 26px 'Century Gothic', Arial, Helvetica, sans-serif;
clip: rect(0, auto, 18px, 0); /* 裁切:保留上方 0 至 18px 區域(即上半部) */
}
.text-container {
width: 28em;
height: 5em;
margin: 1em auto;
position: relative; /* 為絕對定位子元素建立定位基準 */
background: #F6F6F6;
}
.textBottom 在前、.textTop 在後,但因兩者皆為 position: absolute 且座標相同,後者會覆蓋前者。配合 clip 裁切,各自露出不同區塊。.textTop:rect(0, auto, 18px, 0) → 顯示 y=0 到 y=18px 區塊(上半部).textBottom:rect(18px, auto, auto, auto) → 顯示 y=18px 以下區塊(下半部)position: relative:建立絕對定位參考系,確保兩文字層精確對齊。經測試通過:Firefox 1.5、IE 6.0、Opera 8.5、IE 5.01。現代瀏覽器(Chrome、Firefox、Edge、Safari)均完整支援 clip。
註:CSS Masking Module Level 1 引入 clip-path 作為更強大的替代方案(支援多邊形、SVG 路徑),新專案建議優先考慮 clip-path,但 clip 仍廣泛支援於舊專案維護中。
@keyframes 動態改變 clip 數值clip 屬性雖屬舊規範,但以極簡代碼實現「文字局部著色」效果,無需 JavaScript、無需圖片、無額外 DOM 節點。掌握其「疊放同內容、差異裁切區域」的思維模型,能啟發更多純 CSS 視覺特效創作。