Code Demon Code Demon - 2 months ago 9
CSS Question

change the label color if checkbox is checked and red if checkbox is unchecked

I'm trying to create a custom checkbox since its hard to style the native html checkbox so below is what I have tried. The checkbox is checked and unchecked when I click the label but I cant change the border color of the label when the input checkbox is checked and unchecked. Any help, ideas, suggestions, recommendations is greatly appreciated.



input[type="checkbox"]{display:none;}
label{
border:1px solid red;
width: 15px;
height:15px;
display:block;
}
label + input:checked{
border-color: blue;
}

<div>
<label>
<input type="checkbox">
</label>
</div>




Answer

You can't do what you want with that hierarchy (without JavaScript) as there is no parent selector. You'd need to move the label after the checkbox and then use the adjacent sibling combinator +:

input[type="checkbox"] {
  display: none;
}

label {
  border: 1px solid red;
  width: 15px;
  height: 15px;
  display: block;
}

input:checked + label{
  border-color: blue;
}
<div>
  <input id="cb" type="checkbox">
  <label for="cb"></label>
</div>

Comments