I want to store a hex value of color in data-theme attribute like
document.body.setAttribute("data-theme", "#a20000")
How do I use this value in CSS file like following
body[data-theme] {
---theameColor: "data-theme";
}
I want to create an variable that will be used to style all other classes.
I tried this method but it is not working
body[data-theme] {
---theameColor: "data-theme";
}
2
Answers
I don’t think you can do that entirely in the way you describe, but it can be achieved by using that variables set in
:root
and changing the variables values when.I would perhaps recommend a more declarative approach where you could (in theory) have many themes. Note how the CSS defaults to the standard values if no theme is matched (such as the "light" theme)
Yeah, using
:root
in CSS is the best way to do that.If you want to set attribute value using CSS, that’s impossible and not the right way for the programming.
In CSS, you cannot directly set attribute values for HTML elements. CSS is primarily used for styling and layout purposes. Attribute values are typically set in the HTML markup itself. Either you can do it with Javascript.
But I would like to know why you encountered this kind of issue. 😉