css - 使用 attr 设置与 CSP 一起使用的内联 css 变量

标签 css content-security-policy css-variables

我在想如何在不使用内联样式的情况下使用 css 变量。我以为我可以使用这个:

[data-color] {
    --color: attr(data-color color, green);
}
* {
    color: var(--color, blue);
}
<div data-color="red">hello</div>

似乎 attr 仅适用于伪选择器(并且可能仅适用于 content: 属性),但 MDN attr page说:

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.


甚至有演示,但它在 Linux 上的 Chrome 中不起作用,所以对我来说没有用。它甚至不适用于 Linux 上的 Firefox。
有没有其他方法可以在没有内联样式和不写动态的情况下使用 css 变量 <style></style>和随机数?

最佳答案

还没有。在同一个链接中,您可以阅读:

Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.


仍然没有浏览器支持 attr()对于不同于内容的属性,也不支持类型或单位。
值得注意的是,您可以使用 attr()在 CSS 变量中,但稍后需要与内容一起使用。 CSS 变量只是一个中间值,所以我们不评估基于变量的支持,而是基于将使用该变量的属性。

[data-color] {
  --color: attr(data-color);
}

*::before {
  content: var(--color, "default");
  color:blue;
}
<div data-color="red">hello</div>

关于css - 使用 attr 设置与 CSP 一起使用的内联 css 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64587414/

相关文章:

jquery - CSS 更大的可点击 href 区域

javascript - child UL 对父亲 LI 动画的奇怪行为

html - 全屏背景html

google-chrome-extension - Chrome 扩展 list V3 远程托管代码

css - CSS 变量和计算错误 : How can I get error output?

javascript - 使用范围 slider 调整线性渐变

JavaScript - 创建自定义元素并应用标准样式

css - CSP 样式-src : 'unsafe-inline' - is it worth it?

jsonp - 如何安全地将 script-src 与已知的 JSONP 端点主机(如 syndication.twimg.com)结合起来?

css - 如何将 `inherit` 值设置为 CSS 自定义属性?