Κανόνας @scope CSS
- Προηγούμενη σελίδα scale
- Επόμενη σελίδα scroll-behavior
定义和用法
CSS @scope
规则允许您选择特定 DOM 子树中的元素。
通过此 @ 规则,您可以精确地定位元素,而无需编写过于具体的选择器。
此 @ 规则还减少了选择器与 DOM 结构之间的耦合。
实例
例子 1
在这里,我们使用两个独立的 @scope
块来匹配 .ex1 类和 .ex2 类中的 <a> 元素。:scope 用于选择和设置作用域根本身的样式。在此示例中,作用域根是应用了类的 <div> 元素:
@scope (.ex1) { :scope { background-color: salmon; padding: 10px; } a { color: maroon; } a:hover { color: blue; } } @scope (.ex2) { :scope { background-color: beige; padding: 10px; } a { color: green; } }
See the following HTML:
<div class="container"> <div class="news"> <h2>Some header</h2> <img src="example.jpg" alt="Some image"> </div> </div>
There are some nested <div> elements. If we want to set styles for the <h2> and <img> elements in the above container/news section, we must write the following content (without using @scope):
Example 2
.container .news h2 { color: green; } .container .news img { border: 2px solid maroon; }
Using @scope
Rules, you can precisely locate elements without writing overly complex selectors, as shown below:
Example 3
Here, we set .container as the root scope of the @scope rule for <h2> and <img> elements within the .container component:
@scope (.container) { h2 { font-size: 30px; color: green; } img { border: 5px solid maroon; } }
@scope
Rules contain one or more rule sets and can be used in two ways:
- As an independent block in CSS, in this case, it contains a leading part, including the scope root and an optional scope limitation selector - these define the upper and lower boundaries of the scope.
- As an inline style within the <style> element in HTML, in this case, the leading part is omitted, and the included rule set is automatically applied to the parent element of the <style> element.
Example 4
"Donut scope" is only for elements between two elements in the ancestor tree. Here is an example:
@scope (.container) to (.news) { h2 { font-size: 30px; color: green; } img { border: 5px solid maroon; } }
CSS syntax
@scope (Scope root) { Rule set }
or
/* Donut scope */ @scope (Scope root) to (Scope limitation) { Rule set }
Browser support
The numbers in the table represent the first browser version to fully support the @ rule.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
118 | 118 | Δεν υποστηρίζεται | 17.4 | 104 |
- Προηγούμενη σελίδα scale
- Επόμενη σελίδα scroll-behavior