Search code examples
svgbackgroundbackground-color

Set background color to text inside circle element of svg


This is my SVG structure:

<svg viewBox="-2 -2 40 40" class="circular-chart yellow" width="auto" height="auto">
        <path class="circle-bg" d="M18 2.0845
            a 15.9155 15.9155 0 0 1 0 31.831
            a 15.9155 15.9155 0 0 1 0 -31.831"></path>
        <path class="circle" stroke-dasharray="21, 100" d="M18 2.0845
            a 15.9155 15.9155 0 0 1 0 31.831
            a 15.9155 15.9155 0 0 1 0 -31.831"></path>
        <text x="18" y="20.35" class="percentage">93</text>
</svg>

This code output is :

enter image description here

Now I want to set a background around of number inside circle like this:

enter image description here

As you can see I want only a brown color around the number 156 in this example.

I saw these questions in StackOverflow:

Background color of text in SVG

Default background color of SVG root element

Do you have any experience with that?

Thanks in Advance.


Solution

  • The simplest thing is just to add a circle as the first element and colour that. Everything else will then draw on top.

    .circle {
      fill: none;
      stroke: green;
      stroke-width:6px;
      stroke-linecap: round;
    }
    
    .circle-bg {
      fill: none;
      stroke: grey;
      stroke-width:6px;
    }
    
    .text-bg {
      fill: tan;
    }
    
    .percentage {
      fill: orange;
      font-size: 8px;
      font-family: sans-serif;
      text-anchor: middle;
    }
    <svg viewBox="-2 -2 40 40" class="circular-chart yellow" width="auto" height="auto">
            <circle class="text-bg" cx="18" cy="18" r="15"/>
            <path class="circle-bg" d="M18 2.0845
                a 15.9155 15.9155 0 0 1 0 31.831
                a 15.9155 15.9155 0 0 1 0 -31.831"></path>
            <path class="circle" stroke-dasharray="21, 100" d="M18 2.0845
                a 15.9155 15.9155 0 0 1 0 31.831
                a 15.9155 15.9155 0 0 1 0 -31.831"></path>
            <text x="18" y="20.35" class="percentage">93</text>
    </svg>