用于下一个匹配兄弟的CSS3选择器

时间:2017-11-13 08:29:56

标签: html css css3

我正在尝试为以下HTML提供CSS3选择器:

<input data-type="fillpart" type="checkbox" name="cough, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“fever, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>

所有元素都是兄弟元素,...可能还有其他元素。有问题的元素总是按三(3)的顺序排列。目前,我有CSS如下:

fillpart {
  background: #a5d2a5;
}

它为<fillpart>内的文本着色,而标记本身显然被忽略,因为它不是浏览器支持的内容。我想根据前一个标记是否与input[checked='true']false匹配来替换背景值。

这可以用CSS3吗?

谢谢

2 个答案:

答案 0 :(得分:1)

要在选中的输入字段后设置元素样式,可以使用CSS next-selector(+):

fillpart {
    background-color: #a5d2a5;
}

input:checked + ignore + fillpart {
    background-color: red;
}

这将使fillpartignore之后checked input-field具有红色背景颜色

修改

实际上,您可以使用~ - 选择器,它选择前面带有选中输入字段的每个fillpart元素:

fillpart {
    background-color: #a5d2a5;
}

input:checked ~ fillpart {
    background-color: red;
}

答案 1 :(得分:1)

您可以在选择器中使用加号(+):

input[checked="false"] + ignore + fillpart

查看下面的示例:

fillpart {background: #a5d2a5;}
input[checked="false"] +ignore+ fillpart{background: red;}
<!DOCTYPE html>
<html>
<body>
  <input data-type="fillpart" type="checkbox" name="cough, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“fever, " checked="false">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>

</body>
</html>