<h1>Scope Proximity</h1> <p class="support"> ⚠️ Your browser does not support the <code>@scope</code> rule. Try viewing this demo in Chrome Canary with the <strong>experimental web platform features</strong> flag. </p> <div class="dark-theme"> <!-- <h2>with scope</h2> --> <p>The dark-theme link should be <a href="#">lightcyan</a></p>
<div class="light-theme"> <p>The light-theme link should be <a href="#">mediumvioletred</a></p> <div class="dark-theme"> <p>The dark-theme link should be <a href="#">lightcyan</a></p> </div> </div> <p> With <code>@scope</code>, we can ensure that the 'nearer' scope wins, giving us the correct result no matter how these scopes are nested.</p> </div>
<!-- <div class="no-scope dark-theme"> <h2>no scope</h2> <p>The dark-theme link should be <a href="#">lightcyan</a></p>
<div class="no-scope light-theme"> <p>The light-theme link should be <a href="#">mediumvioletred</a></p>
<div class="dark-theme"> <p>The dark-theme link should be <a href="#">lightcyan</a></p> </div> </div> <p> Without <code>@scope</code>, the dark-theme link color will always win since it is defined later in the CSS, with the same specificity. </p> </div>
<p> Scope <strong>proximity</strong> helps resolve conflicts when two scopes overlap. In this case, the nested/overlapping light and dark themes both define link colors using the same selector (and same specificity). Without scope, the later rule takes precedence. With scope, the 'closer' scope root has priority. </p> -->
<article class="media"> <img src="https://assets.codepen.io/15542/mia.jpg" alt="Miriam speaking" height="300" width="300" /> <div class="inner"> <h2 class="title">Outer Title is in-scope</h2> <p> This title, image, and paragraph fall <em>between</em> a scope-root (<code>.media</code>) and lower-boundary (<code>.content</code>), so the scoped styles apply. </p> <div class="content"> <h3 class="title">Inner Title is out-of-scope</h3> <img src="https://assets.codepen.io/15542/sad.jpg" alt="girl, pouting" width="2220" height="1248" /> <p> This image, title, and paragraph are inside (<code>.media</code>), but there is an intervening boundary (<code>.content</code>) that ends the scope. </p> </div> </div> </article>
<section> <style> @scope to (article) { :scope { border: thin dotted mediumvioletred; padding: 1em; } .title { font-family: fantasy; &::before { content: '✅ '; } } p { font-style: italic; } } </style> <h2 class="title">Title in the section scope</h2> <p>This paragraph is also in the section scope.</p> <hr> <article> <h3 class="title">Nested article titles are not in scope</h3> <p> Paragraphs inside the article are also out-of-scope! Yay for lower boundaries! Yay for implicit scopes! </p> </article> </section>
总结
使用 @scope 定义特定的模式或组件及其块元素关系。这些可以是广泛的(整个主题)或狭窄的(单个按钮),有时可能会重叠。元素属于多个作用域是可以的,但每个作用域都特定于 DOM 的某个片段。