skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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. 😉

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search