2

I have a list of checkboxes and labels. I'm using this CSS to apply a style to the label when the checbox is checked:

input[type=checkbox]:checked + .CheckLabels {background-color: green;}

When I order my HTML like this:

<input type="checkbox" name="C" id="checkC" value="C" checked>
<label class="CheckLabels" for="checkC">C</label>
<input type="checkbox" name="D" id="checkD" value="D" checked>
<label class="CheckLabels" for="checkD">D</label>

It works as intended: clicking the C label adds or removes a green style. However, when I put label before the input, clicking the label causes the following label to have the style applied/removed. Ie: Clicking the C label adds or removes the green from the D label (though the proper checkbox is still checked.)

<label class="CheckLabels" for="checkC">C</label>
<input type="checkbox" name="C" id="checkC" value="C" checked>
<label class="CheckLabels" for="checkD">D</label>
<input type="checkbox" name="D" id="checkD" value="D" checked>

Why is this happening? I'm not particularly attached to the order of the labels and checkboxes, since I'll be using display:none. But it would be nice to know what is going on.

drenl
  • 1,321
  • 4
  • 18
  • 32
  • If you're just trying to understand the `+` selector, this question is a duplicate of https://stackoverflow.com/questions/1139763/what-does-the-plus-sign-css-selector-mean – Michael Coker Jul 01 '17 at 22:57

2 Answers2

0

That is related to the fact that the a+b selector selects the b placed directly after the a.

Therefore (when labels are put before inputs) the label right after the C input is the D label.

Vivick
  • 3,434
  • 2
  • 12
  • 25
0

+ is a sibling selector. It specifically selects for A + B, in that order, i.e., it selects element B when it follows element A.

In form, it's analogous to the descendant selector, e.g., div p, which selects any p inside a div, and the direct descendant selector, e.g., div > p, which selects a p only if it's the direct child (and not grandchild) of a div.

The + is a direct sibling, but there's also a useful general sibling selector, e.g., p ~ p would select any p preceded by a p under the same parent.

Check out the MDN article on this specifically, and then read around on related selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors

denmch
  • 1,446
  • 12
  • 20