SVG: Use Attributes or CSS to style?

一曲冷凌霜 提交于 2020-05-24 20:17:09

问题


In HTML it is recommended to seperate 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?

  • <circle fill="yellow" />
  • or <circle style="fill: yellow;" />

回答1:


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.




回答2:


I arrived here because I was trying to remember whether attributes or styles have greater precedence. This is one practical reason why you'd want one over another.

Attributes get applied as "presentation hints", as if they were the first of the cascading style sheets. In other words, this gives them lowest precedence.

Thus the precedence, from lowest to highest, is

  1. attributes
  2. CSS style sheets
  3. inline styles

It's a little confusing that an inline style has much greater precedence than the attribute it's next to. (I keep having to look this up!)

There aren't going to be any new presentation attributes, and we are encouraged to use CSS styling instead, but it doesn't sound like presentation attributes are going away anytime soon.

More detail can be found in the Presentation Attributes section of the Styling chapter of the SVG standard.




回答3:


The difference is always if it's content or it's presentation.

If the circle is content and it has to show whether or not there css available, then the first option is the one.

But if the circle is just part of the site disign and doesn't add anything to the content, then it should be the second option. Or use a css class.




回答4:


I have found Presentation Attributes vs Inline Styles on css-trick really useful for this.

From it:



来源:https://stackoverflow.com/questions/6525405/svg-use-attributes-or-css-to-style

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!