SVG circle with multicolor stroke

At some point you may want to have an object (circle, rectangle, line etc.) that has a multicolor stroke (border).

By now SVG does not have such option but we can take advantage of another feature: stroke-dasharray. This CSS attribute allows to create dashed stroke with specified dash width and distance between dashes. By overlapping objects with different strokes we can achieve multicolor stroke.

Lets say we want a circle with 3-color stroke: yellow, red and blue. Let the dash width be 10px. First we create a circle with normal yellow stroke.

<svg xmlns="http://www.w3.org/2000/svg" height="220">
    <circle class="stroke-yellow" cy="110" cx="110" r="100"></circle>
</svg>
circle {
  stroke-width: 3;
  stroke-opacity: 1;
  fill: none;
}

circle.stroke-yellow {
  stroke: yellow;
}

This way we get a circle with yellow stroke

multicolor-one

Next step is to add second layer of color (red):

<svg xmlns="http://www.w3.org/2000/svg" height="220">
    <circle class="stroke-yellow" cy="110" cx="110" r="100"></circle>
    <circle class="stroke-red" cy="110" cx="110" r="100"></circle>
</svg>
circle {
  stroke-width: 3;
  stroke-opacity: 1;
  fill: none;
}

circle.stroke-yellow {
  stroke: yellow;
}

circle.stroke-red {
  stroke: red;
  stroke-dasharray: 20,10;
}

Now red color is dominating.

multicolor-two

The last step is to cover half of red color with blue:

<svg xmlns="http://www.w3.org/2000/svg" height="220">
    <circle class="stroke-yellow" cy="110" cx="110" r="100"></circle>
    <circle class="stroke-red" cy="110" cx="110" r="100"></circle>
    <circle class="stroke-blue" cy="110" cx="110" r="100"></circle>
</svg>
circle {
  stroke-width: 3;
  stroke-opacity: 1;
  fill: none;
}

circle.stroke-yellow {
  stroke: yellow;
}

circle.stroke-red {
  stroke: red;
  stroke-dasharray: 20,10;
}

circle.stroke-blue {
  stroke: blue;
  stroke-dasharray: 10,20;
}

This way we got a circle with multicolor stroke.

multicolor-three

There are 2 things to take in account:

  • Start with lighter colors. Dark colors should be added in the end. This is because objects may have smooth borders and some light pieces may end up with dark borders
  • In order to find out necessary stroke dasharray values do:
    • Decide on dash width (be it X)
    • Let C be the number of colors
    • First circle should not have dasharray attribute
    • Second circle will have dasharray attribute set as (C-1)*X,1*X
    • Third circle will have dasharray attribute set as (C-2)*X,2*X
    • and so on up to last circle

multicolor-circle

A circle with a multicolor stroke. Some stroke’s dashes seem to be bordered by darker colors (ex. blue border around yellow)