Setting background color of SVG using CSS

2.4k views Asked by At

First time posting here, so treat me gently. :)

I have an SVG image on my site which has a transparent background -

<img class="img-responsive center-block" src="images/pritchservices.svg" alt="Pritch Services Logo" />

Works beautifully on my site. However, due to the transparency, when that image loads in google image search results, due to the transparency, looks terrible.

I have an alternative image (using for fb Open Graph crawler) which is here -

Pritch Services Full Logo

In my crazy mind, this is what I had as a plan:

  • Redo the SVG in Illustrator to include the background color (as per the fb OPen Graph image) - this would then mean the image result in Google would be as expected

  • Have some CSS within my site to set the background color of the SVG to transparent, so it displays nicely (as it currently does on the site)

  • I am assuming I can't just put the SVG markup inline, as although this would give me what I wanted on the page, it wouldn't load the image AT ALL on google image search results?

Is this the way to go, if so, any suggestions on how to implement please; or is there an alternative solution I haven't thought of? Or am I just being too picky?!

Thanks in advance everyone...

1

There are 1 answers

9
Paul LeBeau On

You can't include an SVG via <img> and style it with CSS in your parent document.

  1. You can't style the contents of an <img>, even if it is an SVG
  2. CSS doesn't apply across document boundaries

You have a few options.

  1. Include the version with a background in your page. And then hide it and replace it with the transparent-background version via CSS.

    <div class="logo">
      <img src="logo-with-background.svg" ... />
    </div>
    
    .logo img {
      display: none;
    }
    .logo {
       background-image: url(logo-without-background.svg);
    }
    
  2. Include the background version using <object> then use the DOM to find the background element and hide it.

    var object = document.getElementById("myObject");
    var svgDoc = myObject.contentDocument;
    svgDoc.getElementById("bg").setAttribute("display", "none");
    
  3. Apply a clipping path to the backgrounded version as @Obink suggests. It would work, but it is not the easiest solution though. And it won't work on older browsers that don't support clip paths.