我想知道是否可以使用中间元素定位两个相邻元素?
例如:
<div>
<span class="icon">icon</span>
<input id="input" class="input error" type="text" />
<label for="input"></label>
<div>
当输入有 error 类时,我想将 label 和 span 设为红色。
我通过以下方法使标签变成了红色:
input.error ~ label {
color: red;
}
但是我在跨度方面运气不佳。有人可以告诉我这是否可能吗?如果是这样,请提供帮助。
最佳答案
您可以将 flexbox 与 order
属性一起使用以直观地重新排列元素,同时将 input
作为 DOM 中的第一个元素,因此您可以使用一般兄弟选择器。
div {
display: flex;
}
.icon {
order: -1;
}
input.error ~ * {
color: red;
}
<div>
<input id="input" class="input error" type="text">
<span class="icon">icon</span>
<label for="input">label</label>
<div>
关于css - 是否可以定位 div 的两个相邻邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866512/