Where to put <style> inside SVG?

[亡魂溺海] 提交于 2021-02-18 09:35:23

问题


Sorry if that might come an opinion-based, but I hope there's a right answer..

Where an inline CSS style should be placed inside an SVG document? In the example I provide below I have defined two styles and a circle that uses them.

The first style is defined inside defs tag and the second styles is defined right inside the svg tag.

Both styles are successfully displayed on the circle (at least in Chrome they do, didn't check other browsers though).

My question is which way is more standard?

I think keeping styles in defs keeps the whole SVG more tidy. However, one can claim that I should not use defs tag since no one references the style with <use>

Thanks!

<svg height="100" width="100">
    <defs id="someDefs">
        <style id="style1">
            .blue-fill {
                fill : blue;
            }
        </style>
    </defs>
    <style id="style2">
        .red-stroke {
            stroke : red;
            stroke-width : 12
        }
    </style>
    <circle cx="50" cy="50" r="40" class="blue-fill red-stroke" />
</svg>

回答1:


It doesn't matter. Neither approach is "more standard". <style> elements are not renderable anyway, so there is no real need to put them in the <defs> section

As commented by Paul LeBeau.

After reading this article about style on MDN, that shows an example of a style simply under the SVG root, I am more convinced it is correct to put <style> there rather than under <defs>.

Also, since <defs> tag is indeed for reusable graphical elements that should be rendered, and <style> is not a renderable element, there's no point keeping it there.




回答2:


Graphical elements defined in <defs> are not rendered directly and will be rendered only with use. Hence it is always a good practice to use <defs> if the graphical object is defined for later use. It also increases the readability of the code.

More Information



来源:https://stackoverflow.com/questions/44696405/where-to-put-style-inside-svg

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