- 通过使用 :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 用于在复数选择器中选择当前元素。
- 在此示例中,我们应用颜色:红色;style 设置为伪类 :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>