I was thinking how I can use css variables without using inline styles. I thought that I can use this:
[data-color] {
--color: attr(data-color color, green);
}
* {
color: var(--color, blue);
}
<div data-color="red">hello</div>
It seems that attr work only in pseudo selectors (and probably only on content:
property), but MDN attr page says:
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.
There is even demo but it don't work in Chrome on Linux, so it's of no use to me. It even don't work in Firefox on Linux.
Is there any other way to use css variables without inline styles and without writing dynamic <style></style>
and nonce?
Not yet. In the same link you can read:
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.
Still no browser support the attr()
for properties different than content and also no support for the type-or-unit.
Worth to note that you can use attr()
inside a CSS variable but it need to be later used with content. CSS variables is only an intermediate so we don't evaluate the support based on the variable but based on the property that will use the variable.
[data-color] {
--color: attr(data-color);
}
*::before {
content: var(--color, "default");
color:blue;
}
<div data-color="red">hello</div>