CSS - 偽類 :scope



CSS 偽類:scope 代表用作參考點的元素,允許選擇器訪問給定範圍內的元素。此功能對於模組化和基於元件的 Web 開發尤其寶貴。

  • 透過使用:scope,CSS 樣式可以包含在文件的特定子樹中,防止它們影響該範圍之外的其他元素。

  • 這種隔離確保特定元件的樣式不會與同一頁面上其他元件的樣式衝突或被覆蓋。

  • 這種模組化提高了程式碼的可維護性,並降低了在複雜的 Web 應用程式中出現意外樣式衝突的可能性。

語法

:scope {
    /* css declarations */
}

CSS :scope - 基本示例

以下示例演示了:scope 偽類的用法。

<html>
<head>
<style>
   :scope h1 {
   color: red;
   background-color: lightblue;
   font-size:50px
   }
   :scope p {
   color: blue;
   background-color: beige;
   font-size:20px
   }
</style>
</head>
<body>
   <div>
   <h1>This is a heading</h1>
   </div>
   <div>
   <p>This is a paragraph</p>
   </div>
</body>
</html>

CSS :scope - 身份匹配

在樣式表中使用時,:scope:root 相同,因為目前無法顯式指定作用域元素。

與 DOM API(例如querySelector()querySelectorAll()matches()Element.closest())一起使用時,:scope 將匹配呼叫該方法的元素。

示例

以下示例演示了:scope 偽類和Element.matches() 方法的用法。

  • :scope 偽類用於在複雜選擇器中選擇當前元素。

  • 在此示例中,我們將color: red;樣式應用於:scope 偽類,該偽類目標是 div 元素。

  • 指令碼中的Element.matches() 方法用於檢查元素是否與特定選擇器匹配。

<html>
<head>
<title>:scope and Element.matches() Example</title>
<style>
   :scope {
      color: red;
      font-size: 20px
   }
</style>
</head>
<body>
   <div>
      <p>This is a paragraph.</p>
      <ul>
         <li>This is list item 1</li>
         <li>This is list item 2</li>
         <li>This is list item 3</li>
      </ul>
   </div>
   <script>
      const listItems = document.querySelectorAll('li');
      listItems.forEach(item => {
         if (item.matches(':scope')) {
            item.style.backgroundColor = 'yellow';
         }
      });
   </script>
</body>
</html>
廣告
© . All rights reserved.