0

I was wondering if there's a way to access SVG via CSS when using them like:

.logo {
...
  background-image: url("../VectorImages/logo.svg");
}

I found a few scripts helping to convert svgs to inline SVG, which make them accessible for CSS. Tried it and it's working for img-Tags, but none of these solutions are working when using SVG as a div's background-image.

I'm trying to change the color of the SVG, so what I want to do is

svg path { fill: #000; }
Jmie
  • 97
  • 1
  • 12
  • Possible duplicate of [How to change color of SVG image using CSS (jQuery SVG image replacement)?](http://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement) – urbz Jan 25 '17 at 08:41
  • 1
    No duplicate. It's providing only solutions for using svgs inside img-Tag - unfortunately. – Jmie Jan 25 '17 at 08:52
  • You cannot access the DOM of any image. You can reload a different image if you want to change the colour, or you can change the contents of a data URL – Robert Longson Jan 25 '17 at 11:07

2 Answers2

2

If you are using SCSS – I've made a mixin to handle SVG encoding

Pen: http://codepen.io/jakob-e/pen/doMoML/

SCSS: http://codepen.io/jakob-e/pen/GjgXmK.scss

$color-1: red;
$color-2: green;

$svg-1: '<svg viewBox="0 0 2 2"><circle fill="#{$color-1}" cx="1" cy="1" r="1"/></svg>';
$svg-2: '<svg viewBox="0 0 2 2"><circle fill="#{$color-2}" cx="1" cy="1" r="1"/></svg>';

.class-1 { @include background-svg($svg-1); } 
.class-2 { @include background-svg($svg-2); } 
Jakob E
  • 4,476
  • 1
  • 18
  • 21
1

You can use data URI to import the SVG into the CSS.

HTML

<img src='data:image/svg+xml;utf8,<svg ... > ... </svg>'>

CSS

.logo {
    background: url('data:image/svg+xml;utf8,<svg ...> ... </svg>');
}

Using this method will allow you to use fill to color the SVG while using it as a background.

Note: For more information on implementing SVG using data URI into CSS, see this article.

Matthew Beckman
  • 1,702
  • 2
  • 16
  • 28
  • thanks for your answer. yes, this would be a solution, but it would be great if I could keep my svg's in seperate files, so the css file stays clean. – Jmie Jan 25 '17 at 08:50
  • @Jmie You could create a new CSS file specifically for **SVG** backgrounds. Unfortunately, I am not aware of a solution that would allow you to import **SVG** `data URI` into the CSS document. – Matthew Beckman Jan 25 '17 at 08:56