Reputation: 943
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>");
}
Upvotes: 5
Views: 16909
Reputation: 4560
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>
Upvotes: 2