Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 359
cwahlfeldt Avatar asked Jan 02 '18 20:01

cwahlfeldt


People also ask

What is root pseudo-class?

The :root pseudo-class represents an element that is the root of the document. In HTML, this is always the HTML element.

Are CSS variables global?

First of all: CSS variables can have a global or local scope. Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared.

How do you set a variable value in CSS?

To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.


1 Answers

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>
like image 187
JasonB Avatar answered Oct 15 '22 03:10

JasonB