Reputation: 582
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!
Upvotes: 12
Views: 13552
Reputation: 12139
The syntax would be :
:root.post {
/* cSS declarations */
}
You could have the same stylesheet on 2 pages then apply the posts
class to the HTML element.
:root {
--color-one: yellow;
--color-two: green;
background-color: var(--color-one);
color: var(--color-two);
}
:root.posts {
--color-one: green;
--color-two: yellow;
background-color: var(--color-one);
color: var(--color-two);
}
Updated with child descendant
:root {
--color-one: yellow;
--color-two: green;
background-color: var(--color-one);
color: var(--color-two);
}
:root.posts {
--color-one: green;
--color-two: yellow;
background-color: var(--color-one);
color: var(--color-two);
}
.special {
color: #f0f;
font-style: italic;
}
:root.posts .special {
color: #f90;
font-style: normal;
text-transform: uppercase;
text-shadow: 2px 2px 6px rgba(0, 0, 0, 0.5);
}
<html>
<head>
</head>
<body>
<p>
ghjkghjkg
</p>
<p class="special">Special content</p>
</body>
</html>
Updated with child descendant
:root {
--color-one: yellow;
--color-two: green;
background-color: var(--color-one);
color: var(--color-two);
}
:root.posts {
--color-one: green;
--color-two: yellow;
background-color: var(--color-one);
color: var(--color-two);
}
.special {
color: #f0f;
font-style: italic;
}
:root.posts .special {
color: #f90;
font-style: normal;
text-transform: uppercase;
text-shadow: 2px 2px 6px rgba(0, 0, 0, 0.5);
}
<html class="posts">
<head>
</head>
<body>
<p>
ghjkghjkg
</p>
<p class="special">Special content</p>
</body>
</html>
Upvotes: 6
Reputation: 6378
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>
Upvotes: 9