選擇不含有特定類/屬性/型別的元素的 CSS 選擇器


使用 CSS :not() 偽類,我們可以透過選擇沒有特定值或不匹配選擇器的元素來最佳化我們的樣式。

選擇沒有子選擇器的元素

要選擇沒有子選擇器的元素,請在 CSS 中使用 :not 偽類。

此處,我們有一個子選擇器。CSS 子選擇器用於選擇具有特定父元素的所有子元素。它選擇所有作為 <div> 子元素的 <p> 元素,即。

div>p

但是我們選擇的是沒有此 div>p −

p:not(div>p) {
   background-color: orange;
   font-size: 1.4em;
   font-style: italic;
   color: blue;
}

示例

以下示例說明了 CSS :not 偽類 −

<!DOCTYPE html>
<html>
<head>
   <style>
      p {
         background-color: cornflowerblue;
         color: white;
      }
      p:not(div>p) {
         background-color: orange;
         font-size: 1.4em;
         font-style: italic;
         color: blue;
      }
   </style>
</head>
<body>
   <div>
      <p>Curabitur sapien diam, imperdiet ut est sed, blandit blandit velit. Nunc viverra nunc id ligula ultricies, a fringilla lacus interdum. <span>Sed vel diam at magna pellentesque porttitor.</span></p>
      <h3>Demo</h3>
   </div>
   <p>This is a demo text.</p>
</body>
</html>

選擇不含有某個型別的元素

我們將使用 :not 選擇器選擇不含有某個型別,如下所示 −

div:not(.parent) {
   box-shadow: inset 0 0 24px tomato;
   padding: 2%;
}

在上面,我們有以下父類 −

<div class="parent">
   <div class="one">
      <div class="two"></div>
      <div class="two"></div>
   </div>
   <div class="one"></div>
</div>

示例

讓我們來看一個選擇不含有某個型別的元素的示例 −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin: 2%;
         background-color: cadetblue;
         padding: 10%;
         height: 80px;
      }
      div:not(.parent) {
         box-shadow: inset 0 0 24px blue;
         padding: 2%;
      }
      .parent{
         border: 8px ridge orange;
         color: white;
      }
      .one {
         background-color: lightgreen;
         border: 4px groove gray;
      }
      .two{
         height: 20px;
      }
   </style>
</head>
<body>
   <div class="parent">Parent div
      <div class="one">
         <div class="two"></div>
         <div class="two"></div>
      </div>
      <div class="one"></div>
   </div>
</body>
</html>

更新日期: 31-10-2023

2K+ 次瀏覽

開啟您的 職業 生涯

完成課程後即可獲得認證

開始
廣告
© . All rights reserved.