Is it possible to style an external .svg with css like you would with text? What am I missing? My mark up and css looks like this:
<style type="text/css">
#ob {
color: blue;
}
svg {
fill: currentColor;
}
<object id="ob" type="image/svg+xml" data="czo_svg_icons/czo_extra_closed.svg">Your browser does not support SVG</object>
If you include your svg image by referencing an external file, like you do with the
object
tag, the elements in the svg image are not included to your main documents DOM tree. They comprise their own tree. Therefore, the elements in the external image can't be matched by CSS selectors in the main document.You can style the
object
element like you could most other elements, for example giving it a border. But you can't (this way, at least) access the elements in the external image. In your case, you try to style#ob
'scolor
. That would apply to theobject
s text color, not to any color inside the referenced svg image. On browsers not supporting svg, the "Your browser does not support SVG" notice would probably rendered in blue.The case with your CSS selector for
svg
is similar: CSS selectors in the main document match only to elements in the main document, and there's nosvg
to be found, just anobject
.There are some ways to apply CSS styling to svg elements. The idea generally is to bring the CSS and the svg elements to the same DOM tree, either by getting the svg elements from the external file to the main document or the CSS from the main document to the external file:
svg
element and its child elements directly into the main document instead of referencing an external file. In this case, thesvg
element and its children will be part of the man document's DOM tree, so they're accessible to the main document's CSS.svg
element into your main document and use xlink'suse
to reference an external svg image (rather, a part of it). For the general idea, see this answer or this answer.contentDocument
, see this answer.style
attributes, use astyle
element like in html'shead
or reference an external CSS file with<?xml-stylesheet ... ?>
. For more information, see for example this tutorial.