CSS 偽類 - :has()



CSS :has() 偽類根據元素是否包含匹配特定選擇器的子元素來表示該元素。

語法

:has(<relative-selector-list>) {
   /* ... */
}
:has() 偽類不受 Firefox 瀏覽器支援。

要點

  • 當瀏覽器不支援 :has() 偽類時,只有在 :has() 用於 :is():where() 選擇器內部時,整個選擇器塊才會生效。

  • 您不能在另一個 :has() 選擇器內部使用 :has() 選擇器,因為許多偽元素的存在取決於其父元素的樣式。允許您使用 :has() 選擇這些偽元素會導致迴圈查詢。

  • 偽元素不能用作 :has() 偽類中的選擇器或錨點。

CSS :has() - 相鄰兄弟組合器

以下是如何使用 :has() 函式選擇所有緊跟在 h3 元素之後的 h2 元素的示例 -

<html>
<head>
<style>
   div {
      background-color: pink;
   }
   h2:has(+ h3) {
      margin: 0 0 50px 0;
   }
</style>
</head>
<body>
   <p>You can see it adds bottom margin to h2 elements immediately followed by an h3 element.</p>
   <div>
      <h2>Tutorialspoint</h2>
      <h3>CSS Pseudo-class - :has()</h3>
      <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</p>
   </div>
</body>
</html>

CSS :has() - 與 :is() 偽類一起使用

CSS 選擇器 :is(h1, h2, h3) 選擇所有 h1、h2h3 元素。然後,:has() 偽類選擇這些元素中任何具有 h2、h3h5 元素作為其下一個兄弟元素的元素,如下所示 -

<html>
<head>
<style>
   div {
      background-color: pink;
   }
   :is(h1, h2, h3):has(+ :is(h2, h3, h5)) {
      margin-bottom: 50px ;
   }
</style>
</head>
<body>
   <p>You can see it adds bottom margin to h2 elements immediately followed by an h3 element and h3 element followed by immediately h4.</p>
   <div>
      <h2>Tutorialspoint</h2>
      <h3>CSS Pseudo-class :has()</h3>
      <h5>with :is() Pseudo-class</h5>
      <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</p>
   </div>
</body>
</html>

CSS :has() - 邏輯運算

  • :has(video, audio) 選擇器檢查元素內部是否存在影片或音訊元素。

  • :has(video):has(audio) 選擇器檢查元素是否同時包含影片和音訊元素。

以下是如何使用 :has() 偽類向 body 元素新增紅色邊框和 50% 寬度(如果它包含影片或音訊元素)的示例 -

<html>
<head>
<style>
   video {
      width: 50%;
      margin: 50px;
   }
   body:has(video, audio) {
      border: 3px solid red;
   }
</style>
</head>
<body>
   <video controls src="images/boat_video.mp4"></video>
</body>
</html>

正則表示式和 :has() 類比

CSS :has() 選擇器和帶有前瞻斷言的正則表示式在以下方面具有相似性:它們使您能夠根據特定模式定位元素(或字串),而無需實際選擇匹配該模式的元素(或字串)。

特性 描述
正向先行斷言 (?=pattern) CSS 選擇器 和正則表示式 abc(?=xyz) 都允許您根據另一個元素緊隨其後的情況選擇一個元素,而無需實際選擇該元素本身。
負向先行斷言 (?!pattern) CSS 選擇器 .abc:has(+ :not(.xyz)) 類似於正則表示式 abc(?!xyz)。兩者僅在 .abc 後面沒有 .xyz 時才選擇 .abc
廣告