coding-stylesvg

SVG: Use Attributes or CSS to style?


In HTML it is recommended to separate Content from Style, thus you should create external CSS-Files for your styles. As I am just getting started with SVG I now wonder: Does this rule also apply for SVG?

What is considered better code style?


Solution

  • I would generally prefer <circle fill="yellow" /> to <circle style="fill: yellow;" /> because it's shorter and easily to manipulate with, for example, getAttributeNS(null, "fill").

    But over that I would prefer using a separate style element, just as with HTML, e.g:

      <style>
        circle{
          fill: yellow;
        }
      </style>    
    

    Which has all the same advantages of using CSS, such as making it easy to change the stlye of lots of elements at once.

    You can also put your CSS in an external file and add:

    <?xml-stylesheet type="text/css" href="your_CSS.css" ?>
    

    Before the svg element.