html - SVG <use xlink> 可以用在 CSS 背景图像中吗?

标签 html css svg

在这里我们可以看到 SVGs 可以用在 CSS 背景图片中。

.icon {
   background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="16" viewBox="0 0 64 16"> <circle fill="blue" cx="8" cy="8" r="8"/> <circle fill="red" cx="24" cy="8" r="8"/> <circle fill="yellow" cx="40" cy="8" r="8"/> <circle fill="green" cx="56" cy="8" r="8"/> </svg>');
   background-repeat: no-repeat;
   background-size: auto 100%;
   display: inline-block;
}

但是可以<svg><use xlink:href="svg.svg#mySVG"></use></svg>被实现?这对我来说是无效的 CSS,但我可能只是做错了什么。

最佳答案

正如@Robert Longson 已经评论过的:
不,您不能访问外部 <use>图片中的引用

这适用于:

  • CSS background-image
  • html <img>元素
  • svg <image>元素
  • content 中使用数据 URL 的 css 伪元素属性(property)

来自 mdn 网络文档:Data URLs

Note: Data URLs are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation.

数据 URL 不能包含外部文件引用——它们将被忽略。

所以你只能渲染自包含的元素:

<svg xmlns="http://www.w3.org/2000/svg" width="64" height="16" viewBox="0 0 64 16">
  <defs>
    <circle id="circle" cx="8" cy="8" r="8" />
  </defs>
  <use href="#circle" fill="blue" />
  <use x="16" href="#circle" fill="red" />
  <use x="32" href="#circle" fill="yellow" />
  <use x="48" href="#circle" fill="green" />
</svg>

转换为

.icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='64' height='16' viewBox='0 0 64 16'%3E%3Cdefs%3E%3Ccircle id='circle' cx='8' cy='8' r='8' /%3E%3C/defs%3E%3Cuse href='%23circle' fill='blue' /%3E%3Cuse x='16' href='%23circle' fill='red' /%3E%3Cuse x='32' href='%23circle' fill='yellow' /%3E%3Cuse x='48' href='%23circle' fill='green' /%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-size: auto 100%;
  display: block;
  width: 4em;
  height: 1em;
  outline: 1px solid #ccc;
}

会起作用。但是,您将无法像使用内联 svg 那样选择或设置元素样式。

.icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='64' height='16' viewBox='0 0 64 16'%3E%3Cdefs%3E%3Ccircle id='circle' cx='8' cy='8' r='8' /%3E%3C/defs%3E%3Cuse href='%23circle' fill='blue' /%3E%3Cuse x='16' href='%23circle' fill='red' /%3E%3Cuse x='32' href='%23circle' fill='yellow' /%3E%3Cuse x='48' href='%23circle' fill='green' /%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-size: auto 100%;
  display: block;
  width: 4em;
  height: 1em;
}
<div class="icon"></div>

关于html - SVG <use xlink> 可以用在 CSS 背景图像中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001321/

相关文章:

javascript - BackboneJS + HandlebarsJS - 如何基于css添​​加图片

html - 我需要有关使用 first-child 和 last-child CSS 选择器的帮助

jquery - 语义 UI 模式设置最大宽度?

html - 居中的 div 偏离中心?

svg - 在给定坐标处获取 SVG-Object_s?

CSS Clip-path定位问题

css - CSS 中的 SVG 内联在 FireFox 中不起作用

javascript - 简单的返回顶部按钮不适用于 AngularJS

javascript - 如何将属性值调用到javascript

javascript - 从文件上传设置div背景图片