Search code examples
csssvgbackground-image

Is there a way to target Background SVG specific element to use the fill option?


I have the following code

background-image: url("data:image/svg+xml;charset=UTF-8,<svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' width='47' height='47' viewBox='0 0 120 120'><polygon  class='cls-1' points='120 120 60 120 90 90 120 60 120 0 120 0 60 60 0 0 0 60 30 90 60 120 120 120'/></svg>");

I want to target the cls-1 to change its color but the below code does not seem to effect

.cls-1{
        fill: rgb(39, 60, 117);
      }

Am I doing something wrong??

I can change the code if I put the Color code inside the polygon tag that is

background-image: url("data:image/svg+xml;charset=UTF-8,<svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' width='47' height='47' viewBox='0 0 120 120'><polygon fill='rgb(39, 60, 117)' class='cls-1' points='120 120 60 120 90 90 120 60 120 0 120 0 60 60 0 0 0 60 30 90 60 120 120 120'/></svg>");

I wish to target it separately so that I can let the user change the color and not mess up the SVG code.


Solution

  • You can't, try something like this:

    <style>
        div {
            width:47px;
            height:47px;
            background-image: url("data:image/svg+xml;charset=UTF-8,<svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' width='47' height='47' viewBox='0 0 120 120'><polygon  class='cls-1' points='120 120 60 120 90 90 120 60 120 0 120 0 60 60 0 0 0 60 30 90 60 120 120 120'/></svg>");
        }
    
        div.blue {
            background-image: url("data:image/svg+xml;charset=UTF-8,<svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' width='47' height='47' viewBox='0 0 120 120'><polygon fill='rgb(39, 60, 117)'  class='cls-1' points='120 120 60 120 90 90 120 60 120 0 120 0 60 60 0 0 0 60 30 90 60 120 120 120'/></svg>"); 
        }
    
    </style>
    <div class="blue"></div>