[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 the section.

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.

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-07-01 [AWS] AWS Serverless Application Model (AWS SAM)
2020-07-01 [Functional Programming] Function modelling -- 10. Free Monads
2016-07-01 [RxJS] Drag and Drop example
2014-07-01 [Android] Content provider, ContentResolver
点击右上角即可分享
微信分享提示