首页 > 解决方案 > CSS:如果同级输入没有值,则选择标签并更改颜色

问题描述

如果他们没有,我想让所有人labels都拥有。color: red;sibling input value

我尝试先选择inputs 没有value这样的:

.state-input--red > .input__wrapper > .input__input:not([value])

之后我试图选择他sibling label添加这部分:

~ .input__label

所以我得到了这个选择和设置colorred但它不起作用:

.state-input--red > .input__wrapper > .input__input:not([value]) ~ .input__label {
  color: red;
}

我还尝试通过在之前sibling添加 来指定选择,但它不起作用。这是我的片段:.input__wrapper >label

.state-input--red > .input__wrapper > .input__input:not([value]) ~ .input__label {
  color: red;
}
<div class="input state-input--red">
  <div class="input__wrapper">
    <label class="input__label" for="input00">I should be black, because my siblin input has a value</label>
    <input id="input00" type="text" value="Hello World">
  </div>
</div>

<hr>

<div class="input state-input--red">
  <div class="input__wrapper">
    <label class="input__label" for="input01">I should be red, because my sibling input has no value</label>
    <input id="input01" class="input__input" type="text">
  </div>
</div>

标签: htmlcsscss-selectors

解决方案


选择器 likea ~ b匹配b元素前面的所有兄弟元素a,但在您的标记中,它是:label之前的 who input,这就是它不起作用的原因。

作为一种可能的解决方案,您可以使用 将.input__wrapper元素转换为flexbox容器,然后在代码中flex-direction: row-reverse切换 和 的顺序以保持当前的可视化。labelinput

这样做的选择器.input__input:not([value]) ~ .input__label将按预期工作。


推荐阅读