jquerycsscheckbox

How to style a checkbox nested within a label tag


I usually use the following when setting up a checkbox:

<input ....>
<label for="...">Lorem ipsum</label>

I use the standard method of styling label::before to simulate a style for my checkbox depending on whether the checkbox has been checked or not:

input label{....}
input::checked label{....}

However, a Wordpress plugin is forcing me to use the following syntax:

<label>....
    <input....>
</label>

As CSS in unable to traverse the DOM, my usual pure CSS method won't work here.

Any other suggestions? Perhaps jQuery? Or is there a pure CSS solution I'm missing?


Solution

  • AFAIK, you can't do it with CSS, since it can't traverse the DOM (as you mentioned yourself).
    Unfortunately label:checked doesn't work either.

    So you are looking for a JS/jQuery solution:

    $(function() {
      $(':checkbox').on('change', function() {
        $(this).closest('label').toggleClass('active', $(this).is(':checked') );
      });
    });
    label {
      border: 2px solid red;
    }
    .active {
      border-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <label>
      <input type="checkbox" />
    </label>

    There might be situations where the label is before the input... Then I advice to use the for attribute, to make sure the label is related to the input, the code should then be:

    $(function() {
      $(':checkbox').on('change', function() {
        $('label[for='+ $(this).attr('id') + ']' ).toggleClass('active', $(this).is(':checked') );
      });
    });
    label {
      border: 2px solid red;
    }
    .active {
      border-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <label for="idforcheckbox">This is the label</label>
    <input id="idforcheckbox" type="checkbox" />