coonycoon coonycoon - 4 years ago 96
CSS Question

Detecting multiple checked checkboxes

Without using JavaScript, I want something to happen only when two checkboxes are checked. So something like

#one:checked && #two:checked ~ p {
color: red;
}


for

<input id="one" type="checkbox" name="check"><label for="one">One</label>
<input id="two" type="checkbox" name="check"><label for="two">Two</label>
<p>Thing</p>


which obviously doesn't work. Is there a way to detect both checkboxes without using JS?

Answer Source

Yes, this is possible.

Select the second checkbox if the first one is checked, and then from there select the p element:

#one:checked ~ #two:checked ~ p {
  color: #f00;
}
<input id="one" type="checkbox" name="check"><label for="one">One</label>
<input id="two" type="checkbox" name="check"><label for="two">Two</label>
<p>Thing</p>

Of course you could also generalize the selectors if you don't know the order in advance:

input:checked ~ input:checked ~ p {
  color: #f00;
}
<input id="one" type="checkbox" name="check"><label for="one">One</label>
<input id="two" type="checkbox" name="check"><label for="two">Two</label>
<p>Thing</p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download