Search code examples
csscheckboxstylesline-through

How set "text-decoration: line-through" style for a label that has inside an <input> element?


I have -

<label for="1640801145364"><input type="checkbox" value="foo" id="1640801145364" name="foo">foo</label> 

I need to set "text-decoration: line-through" style (in file.css) for a label that has inside an element. I tried write next in file.css, but it doesn't helps me.

label>input[type=checkbox]:checked {
    text-decoration: line-through;
}

Solution

  • CSS cannot 'go back upwards' in the way you would like to do here, so the checked status of the input cannot affect the overall label.

    There are a few ways round this. You could just swap the input out of the label to be before it, but of course that would alter the look. Instead this snippet puts the contents of the label in a span element and then the state of the input can influence the styling of that as the new element is a following sibling.

    input:checked+* {
      text-decoration: line-through;
    }
    <label for="1640801145364">
    <input type="checkbox" value="foo" id="1640801145364" name="foo">
      <span>foo</span>
    </label>