普通文組 2.5

30天挑戰:「clip-path搭配mix-blend-mode製作疊圖文字」技術記錄

總結

使用 CSS clip-pathmix-blend-mode來做出文字疊圖混色的效果

See the Pen clip-path and mix-blend-mode by Charlie (@Charlie7779) on CodePen.

原理拆解

  • 使用::before::after來寫字,同樣的文字寫兩套
  • 使用clip-path遮去超出圖片範圍的::after文字,並加上mix-blend-mode來為文字上色
    • 算數時間:如何框出clip-path範圍?
    • 算式:clip-path: inset( calc((100% - 320px) / 2) calc((100vw - 400px) / 2) calc((100% - 320px) / 2) calc((100vw - 400px) / 2) );
    • inset代表clip-path形狀設定為矩形(MDN: Defines an inset rectangle.)
    • inset括號內的 4 組數字分別代表clip-path上右下左的起始點(W3C: When all of the first four arguments are supplied they represent the top, right, bottom and left offsets from the reference box inward that define the positions of the edges of the inset rectangle.)
    • clip-path的上下範圍分別是.landing 100%的高度減去圖片的高度(320px)後除以 2 藍色為.landing 100%之範圍 紅色為圖片高度,黑線與.landing 100%高度相同,而黑線高減去圖片高後再除以2,就可得出覆蓋範圍
    • 左右範圍則是100vw減去圖片的寬度(400px)後除以 2,計算原理與高度相同
  • ::before部分的文字就順其自然地讓圖片擋住

補充

GitHub host svg files

.svg檔案推到 GitHub repo 後,點選 raw 即可取得直連位置,在沒有購買 codepen 付費方案時,可做為 online svg hosting 的替代方式

參考文件