htmlcsspostcsscssnext

Change :root variables on different pages with a class


Is it possible to use the :root selector with an ID or Class? I'm trying to flip colors on a different page.

:root {
  --color-one: red;
  --color-two: blue;
}

/* Can something like this happen? */
.posts:root {
  --color-one: green;
  --color-two: yellow;
}

I want to overwrite the root variables when a class is introduced. I know I could achieve with JS but I want to use pure CSS if possible.

Cheers!


Solution

  • The syntax may be a little different from what you have here but sure you can, that's the power of CSS!

    You can override the css variables in any class. You don't need :root for the overrides, and if your overridden values should affect the whole page, add that class to the body tag.

    :root {
      --color-one: red;
      --color-two: blue;
    }
    
    /* Overrides settings in :root */
    .posts {
      --color-one: green;
      --color-two: yellow;
    }
    
    
    
    p {
      color: var(--color-one);
      background-color: var(--color-two);
    }
    <p>
    Test
    </p>
    <p>
    Test
    </p>
    
    <div class="posts">
    <!-- just add this class to the body tag on your other page -->
    <p>
    Test
    </p><p>
    Test
    </p>
    </div>