为什么这个CSS:not()声明过滤掉? [英] Why doesn't this CSS :not() declaration filter down?

查看:179
本文介绍了为什么这个CSS:not()声明过滤掉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择不是特定类的后代的跨度,我们称之为no。这是我的CSS:

I want to select spans that are not the descendants of a specific class, let's call it "no". Here's my CSS:

div:not(.no) span{background-color:#00f;}

这是HTML

<div>
    <span>yes 1</span>
</div>
<div class="no">
        <span>no 1</span>
</div>
<div class="no">
    <div>
           <span>no 2</span>
    </div>
</div>

两个问题:


  1. 为什么我的CSS适用于yes 1和no 2?

  2. 如果切换到通用选择器,为什么整个事件会中断?

  1. Why does my CSS apply to both yes 1 and no 2?
  2. Why does the whole thing break if I switch to a universal selector?

*:not(.no) span{background-color:#00f;}


以下是JSFiddle中的代码: http://jsfiddle.net/stephaniehobson/JtNZm/

Here's the code in JSFiddle: http://jsfiddle.net/stephaniehobson/JtNZm/

推荐答案


  1. span 元素父元素 div 元素没有类没有,不管是否有任何其他祖先有它:

  1. Both of the span elements' parent div elements don't have the class no, regardless of whether any other ancestors do have it or not:

<div> <!-- This is div:not(.no), pretty much a given -->
    <span>yes 1</span>
</div>



<div class="no"> <!-- In this case, although this is div.no... -->
    <div>        <!-- ... this is div:not(.no)! -->
           <span>no 2</span>
    </div>
</div>


  • html c $ c> body ,它们是您的 div span 元素的祖先,满足 *:not(.no)当使用通用选择器(或更确切地说,省略类型选择器时)。这会使 span 元素的全部具有背景颜色。

  • Both html and body, which are ancestors of your div and span elements, satisfy *:not(.no) when using a universal selector (or rather, when omitting a type selector). This causes all of your span elements to have the background color.

    一个解决方法是使用子组合器将您的否定过滤器锚定到 body 元素,如果您的顶级 div 元素将始终是 body 的子元素:

    One solution to this is to anchor your negation filter to the body element using the child combinator, if your top-level div elements will always be children of body:

    body > div:not(.no) span { background-color: #00f; }
    

    jsFiddle demo

    另一个解决方案是简单地使用重写样式。

    Another solution is to simply use override styles.

    这篇关于为什么这个CSS:not()声明过滤掉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆