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)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值