OK – I have a pretty basic page that I’m trying to keep as simple as possible. I have a “theme selector” that chooses between a light and dark theme, and sets the body’s class based on that, basically changing from white/black background/text. I have boxes within that are a different background color that also need to change… is there a way to change the applied class of a child (perhaps many removed) based on the class of the body tag (or any ancestor for that matter) using CSS?
Simple demo:
<body class="dark">
<div class="container">
<div class="differentBG">THIS IS THE BOX I WANT TO CHANGE!</div>
</div>
</body>
I know I can use js (d3 is what I’m using) to apply a class to all of the children, but I want to keep as much in CSS as possible…
You can base rules off of ancestor classes on the body tag as you would any other tag in your markup:
Our
differentBGclass will apply a black background only when the<body>has a class of “dark”.Our
differentBGclass will apply a white background when<body>has a class of “light”.As an added bit of trivia, many developers use this very technique to setup their “JavaScript Disabled” styles:
And then use JavaScript to remove that class when the page loads. Modernizr also uses this method, though it adds classes to the
<html>element to indicate what features the user agent supports.