前面提到我們可以使用 symbol 來重複利用 svg 的圖形,但是問題來了,如果我們在使用的時候想要改變圖形的話該怎麼辦呢?
首先這邊是用簡單的正方形建立 symbol 後重複利用的樣子,但顏色就都是原本設定的顏色。
這邊我們只要把原本指定的 fill 顏色拿掉,另外這邊還使用了 css3 新的 currentColor 的變數,這個變數是可以拿母層 color 的顏色來當變數的,所以把 symbol 裡面的東西改這樣:
<rect width="40" height="40">
<rect x="20" y="20" width="50" height="50" fill="currentColor">
</rect></rect>
然後套一下 css
1 2 3 4 5 6 7 8 9 10 11 12 | .codrops -1 { fill: #4BC0A5 ; color : #A4DFD1 ; } .codrops -2 { fill: #0099CC ; color : #7FCBE5 ; } .codrops -3 { fill: #5F5EC0 ; color : #AEAFDD ; } |
接下來只要在 use 套上設計好的 css 就好了。
這邊能做到的是改變兩個顏色,那如果有更多顏色要調整呢? 我們可以試著使用 css 的變數來設定顏色,在 fill 的部分用這樣寫
<rect width="40" height="40" fill="var(--first-color)">
<rect x="20" y="20" width="50" height="50" fill="var(--second-color)">
<rect x="60" y="60" width="20" height="20" fill="var(--third-color)">
</rect></rect></rect>
再用 css 控制就好了
1 2 3 4 5 | .codrops -1 { --first- color : #FFDD9E ; --second- color : #E89D84 ; --third- color : #FF61C8 ; } |
參考:Styling SVG Content with CSS