2

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

2 Answers 2

2

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.

function setDarkTheme() {
  document.body.setAttribute("data-theme-dark", "");
}
:root {
  --theme-color: #f1f2f3;
  --text-color: #000000;
}

body[data-theme-dark] {
  --theme-color: #494d50;
  --text-color: #FFFFFF;
}

body {
  background: var(--theme-color);
  color: var(--text-color)
}
<body>
  <div>Hello world</div>
  <button type="button" onclick="setDarkTheme();">Set dark theme</button>
</body>

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)

function setDarkTheme() {
  document.body.setAttribute("data-theme", "dark");
}

function setLightTheme() {
  document.body.setAttribute("data-theme", "light");
}

function setRedTheme() {
  document.body.setAttribute("data-theme", "red");
}
:root {
  --theme-color: #f1f2f3;
  --text-color: #000000;
}

body[data-theme="dark"] {
  --theme-color: #494d50;
  --text-color: #FFFFFF;
}

body[data-theme="red"] {
  --text-color: #FF0000;
}

body {
  background: var(--theme-color);
  color: var(--text-color)
}
<body>
  <div>Hello world</div>
  <button type="button" onclick="setDarkTheme();">Set dark theme</button>
  <button type="button" onclick="setLightTheme();">Set light theme</button>
  <button type="button" onclick="setRedTheme();">Set red theme</button>
</body>

Sign up to request clarification or add additional context in comments.

Comments

1

Yeah, using :root in CSS is the best way to do that.

:root {
  --data-theme: #a20000;
}

div {
  background-color: var(--data-theme);
}

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. 😉

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.