:not选择器的用法

222 阅读2分钟

CSS 的 :not 伪类选择器用于排除特定的元素,使得你可以选择不包含某个条件的元素。它接受一个简单的选择器作为参数,并返回不匹配该选择器的所有元素。

基本用法

:not 伪类选择器可以用于任何简单选择器(例如标签、类、ID、属性选择器等),但不能包含复杂的选择器(例如组合选择器、后代选择器等)。

语法

element:not(selector)

示例

  1. 选择所有不是 .active 类的 <div> 元素

    css
    复制代码
    div:not(.active) {
      background-color: lightgrey;
    }
    
  2. 选择所有不是最后一个 <li> 元素的 <li>

    css
    复制代码
    li:not(:last-child) {
      border-bottom: 1px solid #000;
    }
    
  3. 选择所有没有 disabled 属性的 <input> 元素

    css
    复制代码
    input:not([disabled]) {
      background-color: lightblue;
    }
    

综合示例

下面是一个包含多种 :not 用法的示例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:not Selector Example</title>
<style>
  /* 所有不是 .active 类的 div */
  div:not(.active) {
    background-color: lightgrey;
  }

  /* 所有 li 元素,除了最后一个 */
  li:not(:last-child) {
    border-bottom: 1px solid #000;
  }

  /* 所有没有 disabled 属性的 input 元素 */
  input:not([disabled]) {
    background-color: lightblue;
  }
</style>
</head>
<body>
  <div class="active">Active Div</div>
  <div>Inactive Div</div>

  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>

  <form>
    <input type="text" value="Enabled input">
    <input type="text" value="Disabled input" disabled>
  </form>
</body>
</html>

解释

  • div:not(.active) :选择所有不是 .active 类的 <div> 元素,并设置背景颜色为 lightgrey
  • li:not(:last-child) :选择所有 <li> 元素,除了最后一个,并为它们添加一个下边框。
  • input:not([disabled]) :选择所有没有 disabled 属性的 <input> 元素,并设置背景颜色为 lightblue

注意事项

  1. 组合使用:你可以将 :not 伪类选择器与其他选择器组合使用,但 :not 内部不能包含复杂选择器。
  2. 性能:大量使用复杂的 :not 选择器可能会影响性能,应在实际应用中注意。

通过正确使用 :not 选择器,你可以更灵活地进行元素选择,避免使用冗长的选择器链条和不必要的类名。