CSS结构伪类选择器之否定伪类:not()

结构伪类选择器是针对 HTML 层级结构的伪类选择器。

常用的结构化伪类选择器有:

:root选择器、:not选择器、:only-child选择器、:first-child选择器、:last-child选择器、

:nth-child选择器、:nth-child(n)选择器、:nth-last-child(n)选择器、:nth-of-type(n)选择器、

:empty选择器、:target选择器。

这些基本上都很常用,今天着重说下:否定伪类:not()

否定伪类特别有用,在css中, :not选择器 用于匹配非指定元素/选择器的每个元素,语法格式:

:not(selector)

比如:假设我想选择所有 div,除了 id 为 的那个 container。下面代码:

div:not(#container) {
    
    
 color: blue;
}
否定伪类:not()的几个特点:
  1. :not()的优先级是 0,因为它的优先级是由括号里面的参数来定的;
  2. :not()伪类可以同时判断多个选择器,比如input:not(:disabled):not(:read-only)
    {},表示匹配不属于禁用状态同时也不处于只读状态的 input 元素;
  3. not()支持多个表达式,比如:.cs-li:not(li, dd)
    {},还有另外一种写法:.cs-li:not(li):not(dd) {}。但是这两种写法,要考虑兼容性问题;
  4. :not()也支持选择符,比如:input:not(.a > .b) { border: red solid; };

今天遇到一个问题,想把首页除了logo之外的其他元素变黑白,但是用否定伪类却出现很奇怪的问题,其他有部分元素还是彩色的,代码如下:

.home div:not(.logo)
 {
    
    
     -webkit-filter: grayscale(100%); 
     -moz-filter: grayscale(100%); 
     -ms-filter: grayscale(100%); 
     -o-filter: grayscale(100%); 
     filter: grayscale(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);  
     _filter:none; 
     filter: gray;
}

然后改为:效果一样

.home div:not(.header > .logo)
 {
    
    
     -webkit-filter: grayscale(100%); 
     -moz-filter: grayscale(100%); 
     -ms-filter: grayscale(100%); 
     -o-filter: grayscale(100%); 
     filter: grayscale(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);  
     _filter:none; 
     filter: gray;
}

后来换成另一种写法却可以,代码如下:

.home div:not(.header):not(.logo)
 {
    
    
        -webkit-filter: grayscale(100%); 
        -moz-filter: grayscale(100%); 
        -ms-filter: grayscale(100%); 
        -o-filter: grayscale(100%); 
        filter: grayscale(100%);
        filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);  
        _filter:none; 
        filter: gray;
}

后来试验了一下,多少层级关系就要写多少个:not(),例如:

<div class="header">
  <div class="box">
    <div class="logo"></div>
  </div>
</div>

就要写为:

.home div:not(.header):not(.box):not(.logo)

猜你喜欢

转载自blog.csdn.net/joe0235/article/details/134807610
今日推荐