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

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

问题描述

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

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

这是 HTML

<div><span>是 1</span></div><div 类="否"><span>没有 1</span></div><div 类="否">

<span>没有 2</span></div></div>

两个问题:

  1. 为什么我的 CSS 同时适用于 yes 1 和 no 2?
  2. 如果我切换到通用选择器,为什么整个事情都会中断?

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

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

解决方案

  1. 两个 span 元素的父 div 元素都没有类 no,无论是否有其他祖先有没有:

    <div><!-- 这是 div:not(.no),几乎是给定的 --><span>是 1</span></div>

    <div class="no"><!-- 在这种情况下,虽然这是 div.no... -->

    <!-- ... 这是 div:not(.no)!--><span>没有 2</span></div></div>

  2. 作为 divspan 元素的祖先的 htmlbody 都满足*:not(.no) 当使用通用选择器时(或者更确切地说,当省略类型选择器时).这会导致 所有 您的 span 元素具有背景颜色.

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

body >div:not(.no) span { 背景颜色:#00f;}

jsFiddle 演示

另一种解决方案是简单地使用覆盖样式.

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/

解决方案

  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.

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

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