【问题标题】:How to use CSS background url with SVG如何在 SVG 中使用 CSS 背景 url
【发布时间】:2015-07-01 08:46:45
【问题描述】:

我正在尝试链接 background: url(#myid);,ID 将是一个 SVG 元素。

<svg id="myid"></svg>

这甚至可能吗?我做错了吗?

.spesial {
  width: 100px;
  height: 100px;
  background-image: url(#test);
}
<svg id="test" xmlns="http://www.w3.org/2000/svg" width=100 height=100 viewbox="0 0 1500 1500">
  <metadata>Copyright (C) 2015 by original authors @ fontello.com</metadata>
  <path transform="translate(0 500)" stroke="#a4e" d="m929 11v428q-18-20-39-37-149-114-238-188-28-24-46-38t-48-27-57-13h-2q-26 0-57 13t-48 27-46 38q-88 74-238 188-21 17-39 37v-428q0-8 6-13t12-5h822q7 0 12 5t6 13z m0 586v14t-1 7-1 7-3 5-5 4-8 2h-822q-7 0-12-6t-6-12q0-94 82-159 108-85 224-177 4-2 20-16t25-21 25-18 28-15 24-5h2q11 0 24 5t28 15 25 18 25 21 20 16q116 92 224 177 30 24 56 65t26 73z m71 21v-607q0-37-26-63t-63-27h-822q-36 0-63 27t-26 63v607q0 37 26 63t63 26h822q37 0 63-26t26-63z"
  />
</svg>
<div class="spesial">
  Should there not be a background image here?
</div>

我知道我可以设置链接中的所有数据,但是我将无法重用它。 URL
&lt;image href="pic.svg" 那么我的 CSS 样式必须是内联的。

【问题讨论】:

  • CSS Background-image 值只能是 URL。如果您的 html 文件名是例如:'my_file.html',它可能会起作用,而不是如果有一个哈希为:'my_file.html#test' 你只输出图像本身,而不是你可以在 css 中使用它作为网址。
  • 只需将您的 svg 图像保存在 images 文件夹中,然后在您的 css 文件中使用它作为任何其他图像。您可能还需要使用 background-size 属性。
  • 如果你想重用SVG,我能想到的唯一解决方案就是把它保存到一个单独的文件中,并在后台属性中引用它。
  • 我知道我可以将它放在一个单独的文件中(如问题中所述),但是为什么我不能在 html 中链接它?在检查器中可以看到图像已链接但未显示?

标签: html css svg


【解决方案1】:

您还可以将 svg 作为 base64 编码直接包含在 css 中并重用 css 类。

.spesial { background: url("data:image/svg+xml;utf8,<svg...

https://jsfiddle.net/2wjax28a/

【讨论】:

  • 问题中提到这是不想要的,因为那时您只能在一个地方使用它。
  • 但是您可以在多个元素上使用 css 类。像这样:jsfiddle.net/2wjax28a/1
猜你喜欢
  • 1970-01-01
  • 2020-10-01
  • 2015-12-28
  • 2016-08-14
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 2020-11-02
相关资源
最近更新 更多