簡體   English   中英

使用CSS在SVG中樣式化子類

[英]Styling Subclasses in SVG with CSS

我為我們在整個網站中使用的常用圖標嵌入了SVG定義:

<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" display="none">
  <symbol id="icon-1" viewbox="0 0 113.8 113.8">
    <title>Icon 1</title>
    <g>
      <circle class="st2 outter-circle" cx="56.9" cy="56.8" r="55" />
      <line class="st1" x1="56.9" y1="71.5" x2="56.9" y2="86.3" />
    </g>
  </symbol>
</svg>

(在此示例中將其截斷。)

然后,我將其包含在標記中:

<svg viewBox="0 0 100 100" class="campus-icon white five-eighths">
    <use xlink:href="#icon-1"></use>
</svg>

我遇到的問題是通過為SVG對象設置類來為圖標選擇顏色方案。

這些是默認樣式:

.st1 {
    fill:none;
    stroke:#363636;
    stroke-width:0.75;
    stroke-linecap:round;
    stroke-linejoin:round;
    stroke-miterlimit:10;
}

.st2 {
    fill:none;
    stroke:#363636;
    stroke-width:2;
    stroke-miterlimit:10;
}

我嘗試做的是允許SVG對象上的類幫助定義圖標的筆觸顏色:

.campus-icon.white .st1,
.campus-icon.white .st2 {
  stroke: #FFF;
}

這似乎可以在Firefox中使用,但不能在Chrome或Safari中使用。

因為我的圖標有兩種顏色,所以我確實需要弄清楚這點(如果可能的話)。

據我所知,Safari和Chrome不允許我在SVG對象上使用選擇器,然后再在SVG本身中使用選擇器。

為了驗證這一理論,我以這個工作示例( SVG CSS懸停樣式 )為基礎,創建了一個CodePen實例( http://codepen.io/ericrovtar/pen/ZeZqRE )。

有人知道有沒有辦法做到這一點?

謝謝!

-埃里克

不幸的是,Firefox的行為是不符合標准的行為。 被引用元素的組件應該位於具有單獨的CSS解析樹的影子DOM中。

但是有一個小漏洞:影子樹中的元素從其宿主<use>元素繼承樣式。

A-如果您能夠以一種顏色始終應用於筆划,而另一種顏色始終應用於填充的方式來表示圖標,則可以不用為符號定義這些顏色,而僅將它們設置為類別即可。使用元素。

.st1 {
    fill:none;
    stroke-width:0.75;
    stroke-linecap:round;
    stroke-linejoin:round;
    stroke-miterlimit:10;
}

.st2 { /* the element beeing a rectangle instead of a line */
    stroke:none;
}

.campus-icon.white {
   stroke: #FFF; /* could apply to .st1 */
   fill: #DDD;   /* could apply to .st2 */
}

B-對於更復雜的情況,您需要將圖標分成相同顏色的部分,並分別引用它們,即

<svg viewBox="0 0 100 100" class="campus-icon white five-eighths">
    <use class="part-1" xlink:href="#icon-1-part-1"></use>
    <use class="part-2" xlink:href="#icon-1-part-2"></use>
</svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM