SVG为每条路径使用一种颜色

时间:2018-06-06 11:11:04

标签: css svg path

我有一个svg,并且有两条路径

  <path d="M 84.4 53.2 C 75.3 50.1 67.1 48.5 59.6 48.3 C 51.2 48 45.2 47.5 41.5 46.5 C 35.7 45.1 29.9 42.4 23.9 38.4 C 21.6 36.9 19.4 35.2 17.3 33.2 C 19.4 34.2 21.6 35 23.9 35.6 C 27.3 36.5 34.1 37 44.1 37.2 C 53.7 37.3 59.7 37.7 62 38.3 C 70.4 40.3 77 44.2 81.8 49.9 C 82.9 51 83.7 52 84.4 53.2 Z" class="st0" style="fill: rgb(15, 141, 225);"/>
  <path d="M 68.1 7.3 C 79.5 10.1 86.8 16 89.9 24.9 C 91.4 29.2 91.4 36.1 89.8 45.7 C 89.9 45.8 90 46 90.1 46.2 L 90 46 C 90.4 46.7 90.8 47.4 91.2 48.2 C 93.2 52 94.4 56.2 95 60.7 C 95.1 61.3 95 61.8 94.6 62.3 C 94.2 62.7 93.8 63 93.2 63.1 C 92.7 63.2 92.1 63 91.6 62.7 C 91.2 62.3 90.9 61.9 90.8 61.3 C 90.3 57.3 89.2 53.6 87.5 50.2 C 86.8 49.1 86 48.1 85.1 47.1 C 79.7 40.8 72.4 36.5 63.1 34.2 L 63.2 34.3 C 60.8 33.607 54.5 33.599 44.3 33.1 C 34.709 32.63 28.3 32.4 25.1 31.6 L 25 31.6 C 18.9 30.1 14.1 26.9 10.6 22 C 10.2 21.4 9.8 20.7 9.5 20.1 C 9.5 20.1 9.5 20 9.4 20 C 9.3 19.8 9.2 19.6 9 19.3 C 6.6 15.3 5.3 10.8 5 6.1 C 7.4 8.5 10.3 10.1 13.5 10.9 C 17.7 11.9 22.3 12.1 27.3 11.5 C 30.2 11.2 34.7 10.4 40.6 9 C 46.4 7.5 50.9 6.6 54 6.4 C 59 5.8 63.7 6.1 68.1 7.3 Z" class="st0" style="fill: rgb(11, 59, 91);"/>

是否可以使用css单独选择和填充路径?

这有效

.svg-fill {
 fill: red
}

但它填满整个svg。我如何定位各个路径?

2 个答案:

答案 0 :(得分:1)

使用nth-child选择器:

svg path:nth-child(1) { /*OR svg path:first-child OR svg path:nth-of-type(1)*/
  fill:red;
}
svg path:nth-child(2) { /*OR svg path:last-child OR svg path:nth-of-type(2)*/
  fill:green;
}
<svg>
<path d="M 84.4 53.2 C 75.3 50.1 67.1 48.5 59.6 48.3 C 51.2 48 45.2 47.5 41.5 46.5 C 35.7 45.1 29.9 42.4 23.9 38.4 C 21.6 36.9 19.4 35.2 17.3 33.2 C 19.4 34.2 21.6 35 23.9 35.6 C 27.3 36.5 34.1 37 44.1 37.2 C 53.7 37.3 59.7 37.7 62 38.3 C 70.4 40.3 77 44.2 81.8 49.9 C 82.9 51 83.7 52 84.4 53.2 Z"/>
  <path d="M 68.1 7.3 C 79.5 10.1 86.8 16 89.9 24.9 C 91.4 29.2 91.4 36.1 89.8 45.7 C 89.9 45.8 90 46 90.1 46.2 L 90 46 C 90.4 46.7 90.8 47.4 91.2 48.2 C 93.2 52 94.4 56.2 95 60.7 C 95.1 61.3 95 61.8 94.6 62.3 C 94.2 62.7 93.8 63 93.2 63.1 C 92.7 63.2 92.1 63 91.6 62.7 C 91.2 62.3 90.9 61.9 90.8 61.3 C 90.3 57.3 89.2 53.6 87.5 50.2 C 86.8 49.1 86 48.1 85.1 47.1 C 79.7 40.8 72.4 36.5 63.1 34.2 L 63.2 34.3 C 60.8 33.607 54.5 33.599 44.3 33.1 C 34.709 32.63 28.3 32.4 25.1 31.6 L 25 31.6 C 18.9 30.1 14.1 26.9 10.6 22 C 10.2 21.4 9.8 20.7 9.5 20.1 C 9.5 20.1 9.5 20 9.4 20 C 9.3 19.8 9.2 19.6 9 19.3 C 6.6 15.3 5.3 10.8 5 6.1 C 7.4 8.5 10.3 10.1 13.5 10.9 C 17.7 11.9 22.3 12.1 27.3 11.5 C 30.2 11.2 34.7 10.4 40.6 9 C 46.4 7.5 50.9 6.6 54 6.4 C 59 5.8 63.7 6.1 68.1 7.3 Z" />
</svg>

答案 1 :(得分:1)

您的每个路径都有相同的类(在每个路径的末尾,您可以看到它在代码中使用class="st0"定义)。如果您更改类以使每个类都唯一,则可以单独定位它们。

例如,将第二个更改为class="st1",然后以下CSS将使第一个路径为红色,第二个路径为蓝色:

.st0 { fill: red; }
.st1 { fill: blue; }

如果您想使用CSS更改它们,您还应该从每个路径中删除style="fill: rgb(xx, xx, xx);"