First of all I don’t have access to the HTML code and I don’t want to use JavaScrip for this. But here’s my problem: The website has a way to change profile colors. To do this, the div that contains all elements that are to change the color is given an additional class name (e.g. "red"). The existing css code then adjusts the color variable and you can then use this variable inside the "red" class. However, the element for which I want to change the color is completely outside of these classes. Is there a way to check the class name of a div and if the class of that div is "red" then change the properties of another class.
So basically like an if condition: If the name of a class is "red", or if a class with the name "red" exists, then change the properties of class xy
I hope it was somehow understandable. I’m also very very new to programming.
Thanks
HTML
<div class="user red"> /*This color value changes depending of the profile color*/
<a class="title"> Text in red </a>
</div>
<div class="menu">
<a class="dropdown"> Text that should also be red </a> /*This text should change with the same variable*/
</div>
CSS
.user.red {
--color-blue: 218,65,39;
}
.user.green {
--color-blue: 37, 204, 81;
}
.title {
color: rgb(var(--color-blue));
}
I want something like this:
CSS
[if any class with name "red"]
.dropdown {
color: 218,65,39;
}
[if any class with name "green"]
.dropdown {
color: 37, 204, 81;
}
Or something like this:
CSS
.user.red && .menu { /*This gets only applied when it can be applied to both. If not (because there is no class with name "red") it shouldn't be applied*/
--color-blue: 218,65,39;
}
.dropdown {
color: rgb(var(--color-blue));
}
2
Answers
For the type of HTML structure you have shown, yes it can be done:
However, note the caveat.
The above snippet works because the div with class red is on the ‘same level’ i.e. is a preceding sibling of the div with class menu.
If the class red were on the anchor (a) element this would not work.
just use your
.red
class on a parent element, when you define a CSS variable all the children would have access to that variable.so if you have multiple colors on a single page use the
.red
on the specific parent<div class='parent red'>
if you have one color per page u can just add the class to the
<body class="red">
Edit: changed the demo to your specific use case.