【问题标题】:Is it possible to use css variables in a svg background-image?是否可以在 svg 背景图像中使用 css 变量?
【发布时间】:2018-08-01 06:45:33
【问题描述】:

在 SVG 背景图像中使用 CSS 变量时不起作用:

.icon-24 {
  width: 24px;
  height: 24px;
  display: inline-block;
  vertical-align: middle;
  background-repeat: no-repeat;
  background-color: silver;
}

.icon-24-stroke {
  --color-test: red;
  background-image: url("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='none' stroke='var(--color-test)' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' stroke-width='1px'> <circle cx='12' cy='12' r='8' /> </svg>");
}

.icon-24-fill {
  --color-test: red;
  background-image: url("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='var(--color-test)'><circle cx='12' cy='12' r='8' /></svg>");
}
<p>The circle stroke should be red:</p>
<i class="icon-24 icon-24-stroke"></i>
<p>The circle fill should be red:</p>
<i class="icon-24 icon-24-fill"></i>

有没有办法让它工作?

【问题讨论】:

  • Not with url(),除非您使用 JavaScript 而不是 var()。
  • 背景图片是独立于主机页面的文档。 CSS 是每个文档的,因此不仅 CSS 变量不起作用,主机页面中的 CSS 也不起作用。
  • @Robert Longson:这些图像是通过数据 URI 提供的,这些数据 URI 专门设计用于呈现非问题。唯一阻止它工作的是 url() 本身由于历史原因与 var() 不兼容。如果这不是问题,使用 var() 参数化数据 URI 将完美无缺。
  • 即使它是“物理上”在同一个文档中,数据 URL 中的 SVG 也被视为完全一样,就好像它是一个单独的文档一样。
  • 不可能,但有一些helpful alternatives here

标签: css svg css-variables


【解决方案1】:

就像 @BoltClock 在 cmets 中所说,在 urls 中不能使用 css 变量。

【讨论】:

    猜你喜欢
    • 2018-02-24
    • 2015-02-02
    • 2016-01-05
    • 2019-05-27
    • 1970-01-01
    • 2011-11-11
    • 2021-06-30
    • 2021-09-22
    • 2021-08-15
    相关资源
    最近更新 更多