-2

I want when checkbox be checked change label border color but css selector doesn't work.

Example of my code:

label{
  width:36px;
  height:36px;
  padding:9px;
  border:1px solid gray;
  border-radius:36px;
}

#checker:checked label{
  border-color:red;
}
<label for="checker">test</label>
<label for="checker">test</label>

<input type="checkbox" id="checker" checked >
  • 1
    The label is a **previous sibling** of the checkbox, not a **descendant** so you can't use a *descendant combinator* to relate the two selectors! – Quentin Oct 06 '22 at 13:09
  • 1
    Your current `HTML` structure doesn't allow you to do so. There is no *previous sibling* selector in `CSS`. You have **2** options: 1) use `JavaScript` 2) refactor your `HTML` so that the `input[type="checkbox"]` appears before the `labels`. – ThS Oct 06 '22 at 13:09
  • i didn't know we couldn't select the previous item thank you – Alper Uluses Oct 06 '22 at 13:16
  • @AlperUluses — You can, now, so long as you don't care about Firefox. See the duplicate. – Quentin Oct 06 '22 at 13:22

1 Answers1

0

CSS can not select any previous elements. So you have to align your input to be before label. And then change selector to :checked+label

label {
  width: 36px;
  height: 36px;
  padding: 9px;
  border: 1px solid gray;
  border-radius: 36px;
}

#checker:checked+label {
  border-color: red;
}
<input type="checkbox" id="checker" checked/>
<label for="checker">test</label>
Justinas
  • 41,402
  • 5
  • 66
  • 96