Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

css selectors - Why doesn't this CSS :not() declaration filter down?

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;}

Here's the 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>

Two questions:

  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;}
    

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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>
    
  2. 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...