Should you use scoped styling?
Javascript frameworks like Angular, Vue and Svelte support scoped styling at the component level.
In Svelte, you can write styles in a <style>
tag within a .svelte
component. The Svelte compiler will add specific classes to scope styles to that component.
In Vue, you can add an attribute called scoped
to a style
tag. <style scoped>
within an SFC (single file component) enables similar behaviour where the CSS is scoped to that component only.
In Angular, you can write CSS in the context of a component, referencing the stylesheet in the component constructor. Angular provides a specific :host
selector which refers back to the component iself.
I find that this behavior works great for small demos and small projects. You can write CSS directly within the context of the component and automatically scope component styles. This is quick and works well, and it typically leads to fewer of the typical CSS problems where one style is overriding another.
You can code without having to worry about an overall CSS architecture (like BEM/ITCSS for example). Your code is right in the spot where you are probably editing. There are clear benefits to this approach.
However, I believe that for a project of a respectable size there are still good reasons to maintain a separate CSS architecture:
- Theming: To be able to use SCSS in its full capacity without hacky workarounds. I am talking about a system where theme variables can traverse through the CSS in full to generate theme stylesheets with the least amount of unnecessary code
- Code convention consistency: To be able to use established conventions such as BEM and ITCSS – to maintain a proper specificity graph for your project with predictable CSS specificity; if you use too much scoped styling, you run into a risk of an unpredictable specifity vs a global stylesheet
- Portability to other (JS or non-JS) frameworks or contexts: To be able to use the exact same codebase CSS-wise, regardless of the app framework (there are plenty of projects that use the same CSS base for projects in multiple app frameworks at the same time)
To dive a bit further into the last point. For me, the biggest danger in scoping styles to the particular behavior of a Javascript framework is that they become less portable.
There’s so much change in tech. It seems like every year there’s something new. But the expected HTML and CSS doesn’t really change that much. If you make sure your CSS is separate from your JS logic, your styles will be more portable, and you don’t run the risk of having to rewrite your CSS over and over.
So, in conclusion, before you go all-in on scoped styling, consider the portability of your code.
Subscribe to our newsletter
Receive blog highlights and fresh insights into UX/UI and front-end development.
Leave a comment
Your email address will not be published. Required fields are marked *
1 thought on “Should you use scoped styling?”
28 Dec 2020 at 11:32