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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quick reply, mate! It works perfectly.
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; }

2 Comments

How is this different from what I posted 3 hours ago?
you did wrong here prntscr.com/9sdt1i you already specified right selector already so remove beore + label selector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.