csscheckboxcheckedlabel-for

Color background of label with for attribute only when checkbox is checked CSS


There are a lot of examples of coloring All labels when a check box is checked. I need to color just a single label with a "for" attribute

I am trying:

input[type="checkbox"]:checked~label[for=Sign_me_up_for_the_newsletter_and_periodic_alerts] {
  background: green !important;
}
<div class="pull-right">
  <label for="Sign_me_up_for_the_newsletter_and_periodic_alerts">Sign me up for the newsletter and periodic alerts</label>
  <input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
  <br>
  <label class="text-danger" for="I_Agree_to_the_Terms_of_Agreement">I agree to the terms of agreement</label>
  <input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>

When I check the checkbox, nothing happens


Solution

  • It can be done with CSS :has() selector.

    Note, I edited your markup a little, so values of a pair of for= and id= are matched.

    label:has(+ input[type="checkbox"]:checked) {
      color: green;
    }
    <div class="pull-right">
      <label for="newsletter_optin">Sign me up for the newsletter and periodic alerts</label>
      <input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
      <br>
      <label class="text-danger" for="terms_of_agreement">I agree to the terms of agreement</label>
      <input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
    </div>