[CSS] @scope
Video: https://www.youtube.com/watch?v=PkFuytYVqI8&list=WL&index=67
body
└─ article.feature
├─ section.article-hero
│ ├─ h2
│ └─ img
│
├─ section.article-body
│ ├─ h3
│ ├─ p
│ ├─ img
│ ├─ p
│ └─ figure
│ ├─ img
│ └─ figcaption
│
└─ footer
├─ p
└─ img
If you wanted to select the <img>
element inside the <section>
with a class of article-body
, you could do the following:
- Write a selector like
.feature > .article-body > img
. However, that has high specificity so is hard to override, and is also tightly coupled to the DOM structure. If your markup structure changes in the future, you might need to rewrite your CSS. - Write something less specific like
.article-body img
. However, that will select all images inside thesection
.
This is where @scope
is useful. It allows you to define a precise scope inside which your selectors are allowed to target elements. For example, you could solve the above problem using a standalone @scope
block like the following:
@scope (.article-body) to (figure) {
img {
border: 5px solid black;
background-color: goldenrod;
}
}
The .article-body
scope root selector defines the upper bound of the DOM tree scope in which the ruleset will be applied, and the figure
scope limit selector defines the lower bound. As a result, only <img>
elements inside a <section>
with a class of article-body
, but not inside <figure>
elements, will be selected.