带有属性选择器的CSS not()似乎不起作用

时间:2016-10-18 18:03:25

标签: html css css-selectors

我有一个非常简单的选择器,但是当它添加到:not()时,它似乎不再能识别它。

h2:not([random-attribute~="value"] h2){
  color: red;
}
[random-attribute~="value"] h2{
  color: blue;
}
<div class="content">
  <h2>Same valid selector, not working</h2>
  <div random-attribute="value">
      <h2>Valid selector turned blue.</h2>
  </div>
</div>

根据我的理解,如果你在not()内放置一个有效的选择器,你将得到任何h2元素括号内的任何内容。这很直观。

不直观的是,not()中的选择器有效且单独使用时有效,但当添加到not()时,它似乎不起作用。

这不是写这个的有效方法吗?

4 个答案:

答案 0 :(得分:4)

您需要设置所有h2元素的样式,这些元素是非[random-attribute~="value"]然后样式h2的元素的后代。

使用直接子组合器对选择器进行限定也没有什么坏处。

像这样:

&#13;
&#13;
*:not([random-attribute~="value"]) > h2 {
  color: red;
}
[random-attribute~="value"] > h2 {
  color: blue;
}
&#13;
<div class="content">
  <h2>Same valid selector, not working</h2>
  <div random-attribute="value">
    <h2>Valid selector turned blue.</h2>
  </div>
</div>

<h2>some other heading</h2>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

([random-attribute~="value"] h2)语法错误它应该只是([random-attribute~="value"])。见下文:

h2:not([random-attribute~="value"]){
  color: red;
}
[random-attribute~="value"] h2{
  color: blue;
}
<div class="content">
  <h2>Same valid selector, not working</h2>
  <div random-attribute="value">
      <h2>Valid selector turned blue.</h2>
  </div>
</div>

您只应将给定属性放在:not()中,而不是实际元素。

答案 2 :(得分:1)

在选择器级别3中,:not仅支持简单的选择器参数。这可能会在Selectors Level 4中发生变化,但浏览器还不支持它。

  

否定伪类:not()是一个功能伪类   以selector list为参数。它代表了一个元素   它的论证没有代表。

     

注意:在选择器级别3中,只允许一个simple selector   作为:not()的参数。

同时,你可以重写

h2:not([random-attribute~="value"] h2)

作为

:root:not([random-attribute~="value"]) > h2,
:root:not([random-attribute~="value"]) > :not([random-attribute~="value"]) > h2,
:root:not([random-attribute~="value"]) > :not([random-attribute~="value"]) > :not([random-attribute~="value"]) > h2
/* ... repeat until you get deep enough */

然而,在CSS中使用级联选择最具体的样式更自然,而不是像CSS那样使用复杂的选择器。正如kristófbaján所建议的那样,你甚至不需要:not

h2 {
  /* Default styles */
}
[random-attribute~="value"] h2 {
  /* Overriding styles */
}

答案 3 :(得分:0)

我认为你的工作有点过于复杂...... :) 你应该使用:

[random-attribute="value"] h2{
...
}
h2 {
...
}

这应该可以解决您的问题。它不能像你预期的那样工作的原因是not运算符内的选择器应该扩展元素的澄清而不是它的父元素。