CSS 逻辑伪类选择器
这些伪类还旨在为 CSS 选择器带来一些逻辑性和灵活性。
1. not()
到目前为止,我们介绍的每个选择器都有一个共同点:它们都是正向选择器。它们用于识别应该被选择的内容,从而隐式地排除所有不匹配且未被选择的内容。
有时候, 你可能想要选取某个选择器未选中的部分,CSS 提供了否定伪类 :not()。它与其他选择器不太一样,而且在使用上也有一些限制,不过我们先来看一个例子:
假设你想要将一些样式应用于哪些不带有 moreinfo class 的列表项, 你可以这样实现:
li:not(.moreinfo) {font-style: italic;}
<!DOCTYPE html><html><head>  <meta http-equiv="content-type" content="text/html; charset=utf-8" />  <title>Simple styling of a simple document</title>  <style type="text/css">    html { background-color: white; }    li:not(.moreinfo) {font-style: italic;}  </style></head><body><div><p>These are the necessary steps:</p><ul><li>Insert key</li><li>Turn key <strong>clockwise</strong></li><li class="moreinfo"><a href="#">Grip steering wheel with hands</a></li><li class="moreinfo"><a href="#">Push accelerator</a></li><li>Steer vehicle</li><li class="moreinfo"><a href="#">Use brake as necessary</a></li></ul><p>Do <em>not</em> push the brake at the same time as the accelerator.</p></div></body></html>
:not() 在使用时,需要将其附加到一个选择器,然后在括号中填写另一个或另一组选择器,括号中选择器的作用是:描述不想匹配的内容。
继续上面的例子, 让我们来选择所有带有 moreinfo class 且不是列表项的元素。
.moreinfo:not(li) {font-style: italic;}
<!DOCTYPE html><html><head>  <meta http-equiv="content-type" content="text/html; charset=utf-8" />  <title>Simple styling of a simple document</title>  <style type="text/css">    html { background-color: white; }    .moreinfo:not(li) {font-style: italic;}  </style></head><body><div><p>These are the necessary steps:</p><ul><li>Insert key</li><li>Turn key <strong>clockwise</strong></li><li class="moreinfo"><a href="#">Grip steering wheel with hands</a></li></ul><p>Do <em>not</em> push the brake at the same time as the accelerator.  Doing so can cause what <a href="#" class="moreinfo">computer scientists</a> might term a “<a href="#" class="moreinfo">race condition</a>” except you won’t be racing so much as burning out the engine.  This can cause a fire, lead to <a href="#" class="moreinfo">a traffic accident</a>, or worse.</p></div></body></html>
:not() 不能嵌套使用. p:not(:not(p)) 用法是非法的.
:not() 可以串联使用,像这样:
/* 选择所有类名为 link 并且不是列表项也不是段落的元素 */*.link:not(li):not(p) {font-style: italic;} /* 等同于 */*.link:not(li, p) {font-style: italic;}
2. is() 和 where()
假设你想选择所有列表项,无论它们是有序列表还是无序列表。传统做法如下:
ol li, ul li {font-style: italic;}
如果使用 :is(), 可以这样写:
:is(ol, ul) li {font-style: italic;}