Home > Enterprise >  Change parent label background when checkbox is checked
Change parent label background when checkbox is checked

Time:01-18

I want the selection (:checked) to have a different background colour.

Here my example code:

label {
  display: block;
  background: gray;
  border:1px solid black;
  margin-bottom:5px;
  padding:10px;
  cursor: pointer;
}

label   [type="checkbox"]:checked {
  background: yellow;
}
<div >
  <label ><input type="checkbox" /> Yes</label>
  <label ><input type="checkbox" /> No</label>
</div>

My question is related to: enter image description here

label {
  display: block;
  background: gray;
  border:1px solid black;
  margin-bottom:5px;
  padding:10px;
  cursor: pointer;
  user-select: none;
}

label:has([type="checkbox"]:checked) {
  background: yellow;
}
<div >
  <label ><input type="checkbox" /> Yes</label>
  <label ><input type="checkbox" /> No</label>
</div>

If you need browser backward-compatibility support, here's a trick:

label {
  display: block;
  background: gray;
  border:1px solid black;
  margin-bottom:5px;
  padding:10px;
  cursor: pointer;
  overflow: hidden; /* Important so the outline won't overflow */
  user-select: none;
}

label :checked {
  outline: 9999px solid yellow;
}
<div >
  <label><input type="checkbox" /> Yes</label>
  <label><input type="checkbox" /> No</label>
</div>


OP asked me in the comments for a solution tailored for a hidden checkbox.

All that is needed is to use the hidden attribute on the input.
Never use CSS display: none to not render an input element. It is preferable to use the designated attribute.

  • Related