open source weekly ANk 2

@scopedefinition and function

@scope is a css block-level rule that allows you to create a scope that defines a specific areA to which a set of style rules apply. does this remind you of the scope of less and scss? yes, their "scope" is a concept.

basic use

scope consists of two pArts:scope root and scope limit。

  • **scope root (<scope-start>): **defines the node where the style starts to be applied
  • **scope restriction (<scope-end>) (optional): **Define nodes that are not affected by the scope
  • style rules (<rule-list>): styles defined within @scope
@scope [(<scope-start>)]? [to (<scope-end>)]? {
  <rule-list>
}

Example 1: Using Scope Root

Let's say you have a blog post page that contains a post section and a comments section. You want the links in these two blocks to be different colors.

/* 为文章区块定义一个作用域 */
@scope (.article-section) {
  /* 只在文章区块中应用这个样式 */
  a { color: blue; }
}
 
/* 为评论区块定义一个作用域 */
@scope (.comments-section) {
  /* 只在评论区块中应用这个样式 */
  a { color: green; }
}

在这个例子中,.article-section 内的所有链接将会是蓝色,而 .comments-section 内的链接将会是绿色。

示例2:使用作用域限制

现在,假设在你的文章区块中,你有一个特别的引用部分,你不希望在这个部分应用上述的蓝色链接样式。

/* 为文章区块定义一个作用域,但排除引用部分 */
@scope (.article-section) to (.news-section .quote) {
  a { color: blue; }
}

在这个例子中,.article-section 内的链接仍然是蓝色,但文章里 .quote 类中的链接不会受这个作用域限制。(Codepen👇如果链接都显示蓝色,请到Codepen里查看)

https://codepen.io/yohopi/pen/VwgGooo

@scope的高级特性

现在来看一些高级用法。

特殊选择器::scope 和 &

我们可以用 :scope 和 & ****指代作用域根元素,例如

<div class="container">
    <p>这是一段文本。</p>
    <div class="sub-container">
        <p>这是另一段文本。</p>
	      <div>这是一个div</div>
    </div>
</div>

分别测试 :scope 和 &,会发现效果一样,因为此时它们都等价于 .container

@scope (.container) {
    :scope > p { color: red; }
}
@scope (.container) {
    & > p { color: red; }
}

作用域嵌套

嵌套规则:@scope 规则可以嵌套。嵌套规则允许开发者创建复杂的样式结构,同时避免样式的冲突和污染。

/* 外部作用域 */
@scope (.outer-scope) {
  p { color: red; }
 
  /* 内部嵌套作用域 */
  @scope (.inner-scope) {
    p { color: blue; }
  }
}
 

在这个例子中,.outer-scope 内的段落是红色的,但在 .inner-scope 内的段落是蓝色的。

使用数据属性定义作用域

@scope 还可以与HTML的数据属性(如 data-scope)结合使用,以创建更具体的作用域。例如,你可以通过给不同部分的HTML元素添加不同的数据属性,然后在CSS中使用这些属性来定义作用域:

/* 为带有特定数据属性的元素定义作用域 */
@scope ([data-scope='main-section']) {
  p { color: red; }
}
 
@scope ([data-scope='sidebar']) {
  p { color: blue; }
}
 

在这个例子中,data-scope='main-section' 的段落将会是红色,而 data-scope='sidebar' 的段落将会是蓝色。

结语

@scope The introduction of rules is an important progress in the development of CSS. Although browser support is not yet high enough, developers will obviously not wait too long for such an important feature. I believe that mainstream browsers will soon support it.

1.png

专栏资源

专栏介绍:分享CSS新特性和好看的样式设计

专栏地址:👉简明实用CSS技巧