【问题标题】:How set "text-decoration: line-through" style for a label that has inside an <input> element?如何为 <input> 元素内部的标签设置“text-decoration:line-through”样式?
【发布时间】:2021-12-29 18:47:07
【问题描述】:

我有 -

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

我需要为元素内部的标签设置“text-decoration: line-through”样式(在 file.css 中)。我尝试在 file.css 中写入 next,但它对我没有帮助。

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

【问题讨论】:

    标签: css checkbox styles line-through


    【解决方案1】:

    CSS 不能以您在这里想要的方式“向上返回”,因此输入的检查状态不会影响整个标签。

    有几种方法可以解决这个问题。您可以将标签中的输入交换到它之前,但这当然会改变外观。相反,这个 sn-p 将标签的内容放在 span 元素中,然后输入的状态会影响其样式,因为新元素是后续兄弟元素。

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

    【讨论】:

      【解决方案2】:

      我看到你的 CSS,你认为 foo 文本会在输入中,但不是真的这是因为:&lt;input&gt; 不需要结束标记所以他们不能内嵌 foo 文本

      所以首先在 span 中添加一个 foo 文本,这样我们就可以使用 CSS 轻松选择它

      然后我使用了 CSS COMBINATOR ~ https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

      你可以用ALT126来写


      所以如果输入是检查 ...

      ...~ 使我们不设置输入本身的样式,而是设置我们想要的样式(在本例中为 span

      编辑:确保您想要设置样式的所有内容都在输入之后,因为~ 无法选择之前的元素。

      这里是代码

      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>

      【讨论】:

      • 非常感谢您的回答,Laaouatni Anas!
      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2013-05-08
      • 2020-04-25
      • 2022-07-05
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多