CSS - :not()偽類



CSS 偽類函式:not()表示或匹配不匹配給定選擇器列表的元素。它也稱為否定偽類,因為它避免從列表中選擇特定專案。

偽類:not()是一個非常棘手的偽類,會產生意想不到的結果。所以你應該注意它。

使用:not()的一些意外和不尋常的結果如下

  • :not()偽類用於編寫無用的選擇器,例如:use(*)表示它將匹配任何不是元素的元素。這沒有任何意義,因此不會應用任何規則。

  • 它可以提高規則的特異性;例如#foo.not(#bar),將匹配與#foo一樣簡單的元素,但特異性增加了兩個選擇器ID。

  • 從逗號分隔的選擇器列表中,最具體的選擇器的特異性將替換:not()偽類的特異性。

  • 如果你傳遞類似:not(.foo)的內容,則偽類將匹配所有內容,包括基本的 HTML 標籤,例如<html>或<body>。

  • 如果你傳遞:not(table),它將導致匹配tr、tbody、th、td、caption等,因為它們都可以匹配給定的引數 :not(table)。

  • 一次可以否定多個選擇器,例如 :not(.foo, .bar),表示 :not(.foo) :not(.bar)

  • 當作為列表的一部分傳遞的任何選擇器被證明是無效或不受支援時,將導致整個規則無效。為了避免這種情況,你應該使用:is(),因為它具有寬容選擇器列表的特性。

語法

:not(<complex-selector-list>) {
   /* ... */
}

偽類:not()需要一個逗號分隔的一個或多個選擇器的列表作為其引數。該列表不應包含另一個:not()偽元素

CSS :not() 示例

這是一個:not()偽類的示例。

在這個例子中

  • 一個類(.sample)聲明瞭一些 CSS 樣式。

  • :not() 偽類與 h1 元素上的 .sample 類一起使用。

  • :not() 偽類使用 h1 作為引數,因此 CSS 樣式應用於除 h1 元素之外的所有其他元素。

<html>
<head>
<style>
   .sample {
      text-shadow: 2px 2px 3px yellow;
   }

   /* <h1> elements that are not in the class '.sample' */
   h1:not(.sample) {
      background-color: lightblue ;
   }

   /* Elements that are not <h1> elements */ 
   body :not(h1) {
      text-decoration-line: line-through;
   }

   /* Elements that are not <div> and not <span> elements */
   body :not(div):not(span) {
      font-weight: bold;
   }
</style>
</head>
<body>
   <h1>heading with :not(.sample) pseudo-class applied</h1>
   <h1 class="sample">heading with styling applied</p>
   <p>Paragraph, hence :not(h1) and :not(div):not(span) applied.</p>
   <div>div element, hence :not(h1) applied.</div>
</body>
</html>

以下是:not()的另一個示例,其中另一個偽類:nth-child用於在容器中選擇交替的p元素,並應用樣式。

<html>
<head>
<style>
   p:not(:nth-child(2n+1)) {
      font-size: 3em;
   }
</style>
</head>
<body>
   <h1>Heading</h1>
   <p>Paragraph 1</p>
   <p>Paragraph 2</p>
   <p>Paragraph 3</p>
   <p>Paragraph 4</p>
</body>
</html>

在以下示例中,:not()應用於具有類.sample的<li>。因此,樣式應用於沒有.sample類的<li>。

<html>
<head>
<style>
   li:not(.sample) {
      font-size: 2.5em;
      color: red;
   }
   .sample {
      color: green;
      font-weight: 800;
      background-color: lightyellow;
   }
</style>
</head>
<body>
   <h1>Unordered List</h1>
   <ul>
      <li>list item 1</li>
      <li class="sample">list item 2</li>
      <li>list item 3</li>
    </ul>
</body>
</html>
廣告

© . All rights reserved.