跳轉到

建立 2026-09-14 更新 2026-09-14

CSS 與 SVG

Inline SVG 裡的元素就是 DOM,可以用跟 HTML 一樣的選擇器改 fillstroke、做 :hover。用 <img> 引入的檔做不到這件事。

用 class 上色

<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">
  <path class="icon-body" d="M4 12h16"/>
  <circle class="icon-dot" cx="12" cy="12" r="3"/>
</svg>
.icon { width: 48px; height: 48px; }
.icon-body { stroke: #4051b5; stroke-width: 2; fill: none; }
.icon-dot { fill: #e25555; }
.icon:hover .icon-dot { fill: #2e7d32; }

currentColor 跟主題走

把填色設成 currentColor,圖示顏色就跟文字的 color 走:

.btn { color: #4051b5; }
.btn svg { width: 1.2em; height: 1.2em; fill: currentColor; }
<svg viewBox="0 0 24 24"><path d="M4 12h16" fill="none" stroke="currentColor"/></svg>

匯出時若 path 寫死 fill="#000",CSS 很難蓋過。匯出前清掉填色,或在 CSS 用 fill: currentColor !important(最後手段)。

表現屬性 vs CSS

fill="red" 這種表現屬性優先權類似行內樣式,會蓋過一般 stylesheet,但敵不過 style=""!important。主題化時優先把顏色放在 CSS,markup 只留幾何。

svg text {
  font-family: "Noto Sans TC", "Microsoft JhengHei", sans-serif;
  fill: #333;
}

這樣整張教材圖的中文字型一次設完,不必每個 <text> 重寫。

動畫也用 CSS

hover、描邊展開(stroke-dasharray)用 CSS 就夠。時間軸複雜或要跟捲動綁定,再上 JavaScript。見 動畫

進一步學習