html - CSS:如果兄弟输入没有值,则选择标签并更改颜色

标签 html css css-selectors

<分区>

我想让所有的标签都有color: red;如果他们的siblinginput没有

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

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

然后我试图选择他的 sibling label 添加这一部分:

~ .input__label

所以我得到了这个选择并将 color 设置为 red,但它不起作用:

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

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

.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>

最佳答案

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

作为一个可能的解决方案,你可以将你的 .input__wrapper 元素变成一个带有 flex-direction: row-reverseflexbox 容器,然后切换代码中 labelinput 的顺序以保持当前的可视化。

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

关于html - CSS:如果兄弟输入没有值,则选择标签并更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741661/

上一篇:html - 自动拆分 DIV 容器内的长单词,但更喜欢在空格处换行

下一篇:css - 在子组件中覆盖父组件样式

相关文章:

JavaScript 拖放类/ID 问题

html - 使用CSS将按钮与表格中的一行对齐

html - CSS - 为什么这个不可见的边距被应用到我的 <a> 标签 css-button?

html - 如何在 span 标签中做 CSS nth-child?

javascript - AngularJS ngtable 无法正确显示数据

html - 在div容器中输入,不会拉伸(stretch)

html - 在较小的设备上查看时如何在顶部中心显示 Logo

html - 如何删除跨度并在点击时在跨度下播放 youtube 视频?

CSS:如何选择 div 的特定通用孙子?

类别大于 n 的 CSS 目标元素,与其他类别无关