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

Time:12-30

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;
}

CodePudding user response:

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>

CodePudding user response:

I see your CSS, you thought that the foo text will be inside the input, but not really that's because: <input> don't need a closing tag so they can't inner foo text

so first a foo text in a span so with CSS we can easily select it

then I used a CSS COMBINATOR ~ https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

you can write it with ALT126


so if the input is checked ...

...the ~ make us not styling the input itself, but the styling what we want (in this case span)

EDIT: make sure that everything you want to style is after the input because the ~ can't select the previous elements.

here the code

input[type=checkbox]:checked~span {
  text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

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

</html>

  • Related