Adrian Florescu
Adrian Florescu

Reputation: 4492

SVG custom CSS styles for the <use> element in different context

In Firefox, styling a <use> element based on it's parent class works, but in Google Chrome /Safari not. How can I achieve this in a cross browser manner?

SCSS

.column-1 {
  .cls-1 {
    fill: red;
  }
  .cls-2 {
    fill: green;
  }
}

.column-2 {
  .cls-1 {
    fill: blue;
  }
  .cls-2 {
    fill: yellow;
  }
}

HTML

Added the element in the demo, but it's just a svg element with two paths that each has a class name.

<div class="column-1">
    <svg><use xlink:href="#icon-usp_return"></use></svg>
  </div>

  <div class="column-2">
    <svg><use xlink:href="#icon-usp_return"></use></svg>
  </div>

DEMO/Playground

http://codepen.io/anything/pen/kXKZNP?editors=1100

Upvotes: 2

Views: 665

Answers (2)

Cos
Cos

Reputation: 127

You can add fill="currentColor" to the second path of your SVG.

Then in your css file you can write:

.column-1 {
  use {
    fill: red;
    color: blue;
  }
}

.column-2 {
  use {
    fill: green;
    color: orange;
  }
}

Here is a working example based on your code:

https://jsfiddle.net/08hk886w/

Upvotes: 1

west efan
west efan

Reputation: 609

You can make use of path styles in SVG, just add this to each path tag:

style="fill: var(--cls-1)"

Then set a class to you SVG tag, as such:

<svg class="icon1"><use xlink:href="#icon-usp_return"></use></svg>

Finally define your CSS:

.icon1 {
  --cls-1: red;
  --cls-2: green;
}

Fully working example can be found here: http://codepen.io/westefan/pen/grNvoy

Upvotes: 1

Related Questions