如何将颜色应用于SVG Text元素



好的。。。我快疯了。我已经开始试验SVG了。使用SVG并将CSS类应用于它就像一种魅力。我只是不知道我做错了什么,但我就是不能让类处理svg文本元素。我把它一路剥下来,这就是我得到的:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Playground</title>
</head>
<body>
    <style type="text/css">
        .mainsvg {
            height: 320px;
            border: 1px solid red;
            width: 400px;
        }
        .caption {
            color: yellow;
        }
    </style>
    <h2>SVG - Sandbox</h2>
    <div>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="mainsvg">
            <text x="65" y="40" class="caption">Fact</text>
        </svg>
    </div>
</body>
</html>

根据http://www.w3.org/TR/SVG/styling.html#ClassAttribute这应该有效。。。

有什么关于改变或替代的提示吗?

设置类是正确的,但CSS颜色属性对SVG没有影响。SVG使用填充和笔划属性。在你的情况下,你可能只需要改变颜色来填充。这在Firefox中为我显示黄色文本。

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Playground</title>
</head>
<body>
    <style type="text/css">
        .mainsvg {
            height: 320px;
            border: 1px solid red;
            width: 400px;
        }
        .caption {
            fill: yellow;
        }
    </style>
    <h2>SVG - Sandbox</h2>
    <div>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="mainsvg">
            <text x="65" y="40" class="caption">Fact</text>
        </svg>
    </div>
</body>
</html>

这是谷歌为SVG文本着色的最佳结果,为了让像我这样的新手非常清楚,在2022年为SVG文本元素着色,使用笔划和填充。

fill="red"
stroke="#0000FF"

就像使用笔划作为形状的轮廓颜色,使用填充作为形状的内部颜色一样,也可以对SVG中的文本执行同样的操作。

最好的消息是,如果使用fill="currentColor"而不是硬编码的颜色,则可以使用CSS设置SVG文本。

svg {
    color: red;
}

单击"运行代码片段"可查看此答案右侧的示例。

<svg height="202" width="202">
      <circle cx="101" cy="101" r="100"
              stroke="red"
              stroke-width="1"
              fill="none"
              />
<!-- fill="currentColor" if you want to use CSS to set the color of SVG text -->
      <text x="100" y="100" 
            text-anchor="middle"
            fill="red"
            stroke="#0000FF"
            stroke-width="1px"
            alignment-baseline="middle"
            font-variant="all-small-caps"
            font-size="25"
            font-weight="bold" 
            >
        Font is Colored
      </text>

接受的答案对我也不起作用,所以我做了更多的研究,找到了解决方案。如果将SVG <text .../>元素包装在<g .../>(组)元素中,它可以工作:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="mainsvg">
  <g class="caption">
    <text x="65" y="40" fill="currentcolor">Fact</text>
  </g>
</svg>

这将CSS应用于<g>,然后<text>元素将父元素的currentcolor继承到其fill(或stroke)中。

最新更新