This document discusses scoped CSS and proper techniques for scoping styles. It notes that scoping prevents styles from one component affecting others and prevents the need for !important. Scoping can be done through careful class naming, such as BEM or OOCSS conventions. The document then discusses some gotchas with scoping, such as child components having different IDs than parents and the need to still use class selectors to avoid slowing performance. It concludes by recommending scoping for similar structured components but not global ones, and to first use proper class naming before scoping.
3. Why do you need to care about
properly scoping CSS?
- Prevent styles for one component from affecting others
- Prevent people from resorting to using !important
4. How do you properly scope CSS?
… By carefully naming things.
(At least that the way it is before CSS modules)
- Name-spacing, e.g:
• Pure CSS: pure- (pure-button, pure-grid)
- Conventions, e.g.:
• BEM (Block-Element-Modifier)
• OOCSS (Object Oriented CSS)
5. There are only two hard things in Computer Science:
cache invalidation and naming things.
17. Parent components can’t override the styles of child scoped components
Child has a different ID.
18. Parent components can’t override the styles of child scoped components
Child has a different ID.
Solutions:
1. Use deep selectors
2. Remove scoping on child component
23. Scoped CSS != You don’t need to use CSS class at all
Don’t do this.
Browsers will evaluate all h1 elements,
slowing down performance.
24. In the end
I removed all the scoped css and when back to scoping using BEM
- It’s easier to override styles (As how Cascading Style Sheets was designed for)
- It’s easier to see relationships between elements use “Block” prefixes
- And simply because I’m used to it…
Note that this is very personal preference. YMMV.
25. How I think Scoped CSS is supposed to be used
- Don’t scope global components, e.g. buttons. Because you’ll properly want to
override them.
- Start with naming elements with proper CSS class first.
- Use scoped when you have similar components with similar structure e.g.
<UserCard>, <ArticleSummaryCard>. (And then, in these components you
might just use shorter block prefixes like “card-“ instead of “user-card-“ or
“article-card-“).