<分区>
标签 html css css-selectors
<分区>
我想让所有的标签
都有color: red;
如果他们的sibling
input
有没有 值
。
我尝试首先选择 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
元素,但在你的标记中它是label
在 input
之前:这就是它不起作用的原因。
作为一个可能的解决方案,你可以将你的 .input__wrapper
元素变成一个带有 flex-direction: row-reverse
的 flexbox
容器,然后切换代码中 label
和 input
的顺序以保持当前的可视化。
像 .input__input:not([value]) ~ .input__label
这样的选择器将按预期工作。
关于html - CSS:如果兄弟输入没有值,则选择标签并更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741661/