如何在基线下对 CSS 进行 @scope
Firefox 146 now supports @scope in CSS, joining Chrome and Safari, meaning that it’s now supported in all major web browsers, earning it the “Baseline: Newly Available” tag.
Firefox 146 现在在 CSS 中支持 @scope,与 Chrome 和 Safari 一起,这意味着它现在在所有主要网页浏览器中都得到了支持,获得了“基线:新可用”标签。
This @scope at-rule defines a new scope context in CSS. The :scope pseudo-class represents the root of said context (otherwise known as the ‘scope root’), and all this means is that we have some new and exciting ways of writing and organizing CSS, so today I’ll demonstrate the different ways of using @scope and the benefits of each one.
这个 @scope at-rule 在 CSS 中定义了一个新的作用域上下文。:scope 伪类表示该上下文的根(也称为 'scope root'),这意味着我们有一些新的和令人兴奋的方式来编写和组织 CSS,因此今天我将演示使用 @scope 的不同方式及其各自的好处。
You can use an @scope block in any CSS, be it within a stylesheet that you <link> up or a <style> block within HTML. In fact, the latter has some interesting properties we’ll get to.
你可以在任何 CSS 中使用 @scope 块,无论是在你 <link> 的样式表中,还是在 HTML 中的 <style> 块中。事实上,后者有一些有趣的属性,我们稍后会讨论。
Whichever way you use CSS, the rules are, by default, globally scoped. For example, in the demo below, even though the CSS rules are nested within the <main>, they apply to the whole document:
无论你如何使用 CSS,规则默认都是 全局 作用域。例如,在下面的演示中,即使 CSS 规则嵌套在 <main> 中,它们也适用于 整个 文档:
<header></header> <main> <style> header, footer { background: rgb(from green r g b / 30%); } </style> <header></header> <section></section> <footer></footer> </main> <footer></footer>Code language: HTML, XML (xml)
<header></header> <main> <style> header, footer { background: rgb(from green r g b / 30%); } </style> <header></header> <section></section> <footer></footer> </main> <footer></footer>代码语言:HTML, XML (xml)
Styles in a CSS stylesheet are also globally scoped by default.
CSS 样式表中的样式默认也是全局作用域的。
However, @scope can be used to limit the CSS to the ‘scope root’ (which in this case is <main>, because the <style> is a direct child of <main>). In addition, within the @scope at-rule, :scope selects this scope root:
然而,@scope 可以用来限制 CSS 到‘scope root’(在这种情况下是 <mai...