Skip to main content
Home / The Lodge / Everything You Need To Know About SVG / 21: Get Two Colors in a Use

21: Get Two Colors in a Use

We learned that a limitation of using <use> to insert a bit of SVG is that you can't write compound CSS selectors that affect through there. For instance:

<svg class="parent">
  <!-- shadow DOM boundary is effectively here -->
  <use class="child">
     <!-- stuff <use> references gets cloned in here --> 
  </use>
  <!-- end shadow DOM boundary -->
</svg>

That shadow DOM boundary prevents selectors like

/* nope */
.parent .child {
}

from working. Perhaps someday we'll get a working CSS selector to penetrate that shadow DOM boundary, but as of this writing it's not here yet.

You can still set the fill on the <svg> parent and that will cascade down through, but that only gets you one color (remember to not set the presentational fill attribute on those shapes!).

Fabrice Weinberg thought of a neat little technique to get two colors though, exploiting the currentColor keyword in CSS.

Set the fill CSS property on any shapes you like to currentColor:

.shape-1, .shape-2 {
  fill: currentColor;
}

That way when you set the color property on the parent <svg>, that will also cascade through. It won't do anything all by itself (unless you have <text> in there), but currentColor is based off of color so you can use it for other things.

svg.variation-1 {
  fill: red;
  color: orange;
}

svg.variation-2 {
  fill: green;
  color: lightblue;
}

Demo:

See the Pen CodePen Logo as Inline SVG by Chris Coyier (@chriscoyier) on CodePen.

icon-link icon-logo-star icon-search icon-star