【问题标题】:Use css variable into background-image for changing color在背景图像中使用 css 变量来改变颜色
【发布时间】:2021-08-15 19:46:38
【问题描述】:
我想将我的 CSS 变量用于更改 SVG 的填充属性的背景图像。
:root{
--primary: red;
}
input {
background-image: url('data:image/svg+xml,<svg fill="var(--primary)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
background-position: right center;
background-repeat: no-repeat;
}
<input type="text>
【问题讨论】:
标签:
css
svg
background-image
【解决方案1】:
很遗憾,您无法更改 svg fill/stroke 属性,如果用作 background-image。只有当svg 以代码形式存在于 HTML 中时,您才能这样做。
【解决方案2】:
也许没有那么优雅,但你可以做这样的事情。
:root{
--red: url('data:image/svg+xml,<svg fill="red" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
--blue: url('data:image/svg+xml,<svg fill="blue" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
--primary: var(--red);
}
input {
background-image: var(--primary);
background-position: right center;
background-repeat: no-repeat;
}
<input type="text">