2

I am trying to style a custom checkbox on a form; my HTML looks something like this:

<form id="contact">
  <input type="checkbox" id="option1" />
  <label for="option1">Option</label>
</form>

My CSS looks something like this:

form input[type="checkbox"] {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0.2;
}
form label {
  padding-left: 20px;
  position: relative;
}
form label:before {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  left: -10px;
  border: 1px solid #000;
}

I wanted to add a background color when the checkbox is ticked so I added this rule:

input[type="checkbox"]:checked + label:before {
  background-color: #ccc;
}

Which works like I wanted to, but I need to be specific only for the rule to work on a contact form, so I changed it to:

#contact input[type="checkbox"]:checked + #contact label:before {
  background-color: #ccc;
}

This time it does not work. The background does not change when the checkbox is ticked.

My question is what is wrong with the CSS? What am I missing?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Possible duplicate of [How to style a checkbox using CSS](https://stackoverflow.com/questions/4148499/how-to-style-a-checkbox-using-css) – miken32 Aug 13 '19 at 20:20

2 Answers2

1

You were very close. The selector should be:

#contact input[type="checkbox"]:checked + label:before {
  background-color: #ccc;
}

The reason it wasn't working was because #contact isn't an adjacent sibling with the input[type="checkbox"] element. You need to omit the second #contact id selector.

In other words, the selector:

input[type="checkbox"]:checked + #contact label {}

Would attempt to select the following label element:

<input type="checkbox" id="option1" />
<div id="#contact">
   <label for="option1">Option</label>
</div>

Since the input checkbox element doesn't have an adjacent #contact element, nothing was being selected.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

form input[type="checkbox"] {
    position: absolute;
    left: 0;
    top: 0; opacity: 0; }

form label {
    padding-left: 30px;
    position: relative; }

form  label:before {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    left: 0;
    top: 0;
    border: 1px solid #000; }
    
    #contact input[type="checkbox"]:checked + label:before { background-color: #ccc; }
<form id="contact">
       <input type="checkbox" id="option1" />
       <label for="option1">Option</label>
   </form>

Please just update this code #contact input[type="checkbox"]:checked + label:before { background-color: #ccc; }

Ram kumar
  • 3,152
  • 6
  • 32
  • 49