html - How to apply a style to an embedded SVG?


When an SVG is directly included in a document using the <svg> tag, you can apply CSS styles to the SVG via the document's stylesheet. However, I am trying to apply a style to an SVG which is embedded (using the <object> tag).

Is it possible to use anything such as the following code?

object svg { 
    fill: #fff; 

All Answers
  • Translate

    Short answer: no, since styles don't apply across document boundaries.

    However, since you have an <object> tag you can insert the stylesheet into the svg document using script.

    Something like this, and note that this code assumes that the <object> has loaded fully:

    var svgDoc = yourObjectElement.contentDocument;
    var styleElement = svgDoc.createElementNS("", "style");
    styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here

    It's also possible to insert a <link> element to reference an external stylesheet:

    var svgDoc = yourObjectElement.contentDocument;
    var linkElm = svgDoc.createElementNS("", "link");
    linkElm.setAttribute("href", "my-style.css");
    linkElm.setAttribute("type", "text/css");
    linkElm.setAttribute("rel", "stylesheet");

    Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = "@import url(my-style.css)".

    Of course you can directly link to the stylesheet from the svg file too, without doing any scripting. Either of the following should work:

    <?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet href="my-style.css" type="text/css"?>
    <svg xmlns="">
      ... rest of document here ...


    <svg xmlns="">
        <link href="my-style.css" type="text/css" rel="stylesheet" 
      ... rest of document here ...

    Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.

  • Translate

    You can do this without javsscrpt by putting a style block with your styles inside the SVG file itself.

    <style type="text/css">
     polygon { 
        fill: #fff; 

  • Translate

    If the only reason for using the tag to inlcude the SVG is that you do not want to clutter your source code with the markup from the SVG, you should take a look at SVG injectors like SVGInject.

    SVG injection uses Javascript to inject an SVG file inline into your HTML document. This allows for clean HTML source code while making the SVGs fully styleable with CSS. A basic example looks like this:

      <script src="svg-inject.min.js"></script>
      <img src="image.svg" onload="SVGInject(this)" />