Is it possible to set a background image on an SVG element with CSS?

12,321

Your code works fine as you can see below. But you may encounter problems in a case if your SVG will contain same quotes that you're using to place SVG image inside url(). They need to be either quoted like \" or replaced. You can also consider encoding your SVG image using base64 encoding, but it will make your CSS size bigger.

svg {
  background-color: lightgrey;
}
.color {
   fill: blue;
}

.svg-plain {
   background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 43'><path class='color' d='M 55.584673,43.175632 36.75281,22.967243 0,43.175632 40.42403,0 59.71135,20.208389 96,0 Z' /></svg>");
}

.svg-base64 {
   background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA5NiA0Myc+PHBhdGggY2xhc3M9J2NvbG9yJyBkPSdNIDU1LjU4NDY3Myw0My4xNzU2MzIgMzYuNzUyODEsMjIuOTY3MjQzIDAsNDMuMTc1NjMyIDQwLjQyNDAzLDAgNTkuNzExMzUsMjAuMjA4Mzg5IDk2LDAgWicgLz48L3N2Zz4=")
}

.svg, svg {
  width: 100px; 
  height: 100px;
  background-position: center;
  background-repeat: no-repeat;
  background-color: lightgrey;
  margin: 5px;
}
<div class="svg svg-plain"></div>
<div class="svg svg-base64"></div>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 43'><path class='color' d='M 55.584673,43.175632 36.75281,22.967243 0,43.175632 40.42403,0 59.71135,20.208389 96,0 Z' /></svg>
Share:
12,321

Related videos on Youtube

Karai17
Author by

Karai17

I do things sometimes.

Updated on September 26, 2022

Comments

  • Karai17
    Karai17 over 1 year

    Is it possible to target a background-image SVG with CSS?

    .color {
       background-color: #fff;
       color: #fff;
    }
    
    .svg {
       background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 43'><path class='color' d='M 55.584673,43.175632 36.75281,22.967243 0,43.175632 40.42403,0 59.71135,20.208389 96,0 Z' /></svg>");
    }
    
    • isherwood
      isherwood over 6 years
      @Flying, answers go down there.
  • Karai17
    Karai17 over 6 years
    This doesn't seem to be doing what I want it to do. I want the actual SVG paths to be coloured, not just a background.
  • Flying
    Flying over 6 years
    @Karai17 sorry, your question was not clear enough... It is also possible, but in this case you need to either embed your CSS directly into SVG (if you're inserting is as <img> or <object>) or you need to insert SVG directly into document as part of HTML page
  • Karai17
    Karai17 over 6 years
    So there is no way to style the SVG if it is a background image?
  • Flying
    Flying over 6 years
    No, because in this case it is treated as image and not something that have its own internal structure