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!
The :root pseudo-class represents an element that is the root of the document. In HTML, this is always the HTML element.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With