Chris
Chris

Reputation: 261

Change Opacity of non-adjacent non-sibling non-parent div using CSS-Only Checkbox

I have an array of items. I want toggle their opacity or animate them. They're all objects in one div. I'd like to also change the opacity of the entire div and its contents with a toggle. On the same page, I have a div with an array of toggles to accomplish the animations. I'm trying to accomplish this using no javascript — css only.

To simplify things, the codepen below is an example. I want to toggle the opacity of everything in the div containing the blue circle. If the circle svg were adjacent or a sibling of the toggle, I could use a combinator to make it happen. But it's not. I would like to keep my animations in one area and the control panel in another on the same page.

I want to make the light blue div with the blue circle become transparent by unchecking the toggle animation (checkbox) in the green div. There are other intervening divs nested complexly, so it's not a simple task. Let's pretend the div architecture is relatively frozen unless some key edit in selectors will magically make things easier.

I'd be grateful for a link to combinator examples or a more appropriate methodology for how this sort of task can be accomplished using only CSS.

The code that I'm focusing on is at the very bottom of the css column in the codepen and looks a bit like this:

/*  --- Toggle .my-content div opacity  ---  */

input[type="checkbox"] + .my-content {
  opacity: 0.15;
}

input[type="checkbox"]:checked + .my-content {
  opacity: 1;
}

Of course this code doesn't work. What code would?

Checked and Unchecked States with Desired Outcome

Codepen

Upvotes: 0

Views: 97

Answers (1)

bowlowl
bowlowl

Reputation: 467

If your number of items is small, you can move the input to right above the circle and manually target each label through its for attribute.

HTML

<input type="checkbox" id="switch" />
<div class="my-content">
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <circle cx="50" cy="50" r="50" fill="blue"/>
  </svg>
</div>
<div class="my-middle"><p>Other content</p></div>
<div class="my-toggle"><div class="toggle-array-nested-div"><label for="switch">Toggle</label></div></div>

CSS

#switch:checked ~ .my-toggle label[for=switch] {
    background: blue;
}

Upvotes: 0

Related Questions