CSS - 偽類 :is()



CSS 偽類函式:is()接受引數作為選擇器列表,從而目標任何可以被列表中任何選擇器選中的元素。

偽類:is()

  • 簡化了需要編寫的大量選擇器,使其更簡潔。

  • 簡化了節選擇器,即在處理不同級別的 HTML 節和標題時,例如<section>,<article>,<aside><nav>

  • 不選擇偽元素。參考下面的語法,這些是不允許的

    sample-element:is(::before, ::after) {
       display: block;
    }
    
    :is(sample-element::before, sample-element::after) {
       display: block;
    }
    

此偽類最初稱為:matches(和:any())。

偽元素在:is()偽類的選擇器列表中無效。

:is() vs :where()

:is()負責計算列表中所有選擇器的更具體的數量,而:where()的特異性值為0。

寬容的選擇器解析

  • 使用:is()和:where()時,如果其中一個選擇器無法解析,則不會將整個選擇器列表視為無效,而是隻忽略不正確或不支援的選擇器,並使用其餘的選擇器。

  • :is(:valid, :unsupported) - 這將正確解析並匹配:valid,即使瀏覽器不支援:unsupported

語法

:is(<forgiving-selector-list>) {
   /* ... */
}

CSS :is() 示例

下面的例子演示了:is()函式偽類的用法。在這裡,:is()函式偽類應用於h1、h2、h3a元素。因此,無論在何處找到這些元素,都會應用相應的樣式。

<html>
<head>
<style>
   body {
      font: 300 90%/1.4 system-ui;
      margin: 1rem;
   }
   main :is(h1, h2, h3) {
      color: green;
   }
   main :is(a) {
      color: red;
      font-size: large;
   }
</style>
</head>
<body>
   <main>
      <h1>:is() pseudo-class example</h1>
      <h3>Li Europan lingues</h3>
      <a href="">es membres del sam familie</a>. <p>Lor separat existentie es un myth.</p>
      <h2>Por scientie, musica, sport etc, litot Europa usa li sam vocabular.</h2>
      <p>Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.</p>
      <p>At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>
      <h3>Ma quande lingues coalesce</h3>
      <p>li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues.</p>
      <p>It va esser tam simplic quam <a href="">Occidental</a> in fact, it va esser Occidental.</p>
   </main>
</body>
</html>
廣告
© . All rights reserved.