35 ms·
I'm still against inline CSS and what are essentially inline css helper libraries (tailwind etc), but a big part of maintainability is co-location of related co
by ehnto 6y ago
I'm still against inline CSS and what are essentially inline css helper libraries (tailwind etc), but a big part of maintainability is co-location of related code, which inline CSS provides at the cost of readability and control. I feel you can get most of that benefit with well organised SCSS, specifically something similar to the components/contexts model.
For components, you have no styles outside of your component partials, so nothing influences a component except what's targeting it. All targeting is via BEM naming, so no inheritance even for nested components.
So that's components, however sometimes things change depending on their context, which is really messy if you're using inline styles. You end up introducing logic, or you end up with different kinds of components for different contexts and having to maintain them all.
When using components/contexts, if for example a product-card on the checkout needs to look different in some small way. You just have a _checkout.scss file, and in it you target .checkout-page .product-card, and that's it. Simple, clean, no weird inheritance/overriding issues, just hygienic scoping of CSS and one level of inheritance available if needed.
The product-card never has to concern itself with checkouts, and the checkout knows it has a product card so it makes sense that it controls any changes it wants.
I've been using this method for a while now, the majority of the time you end up with ~10-20 small component files, and then 4 or 5 context files with maybe 20 lines in them. You know exactly where all styles affecting your component live, it ends up really clean and easy to maintain.
- nicoburns 6y ago> All targeting is via BEM, so no inheritance even for nested components. If you use (S)CSS modules, then you don't even need to worry about BEM.
- j-krieger 6y agoIf you use CSS Modules, you can not target an elements children with another css module class name. You can‘t know the hash beforehand
- nicoburns 6y agoYou could import the parent CSS module in the child. It might not be a bad idea to make the dependency explicit like that if the components are so tightly coupled.
- fgkramer 6y agoSeconded, when you have a large codebase, BEM selectors end up taking a considerable amount of kB on your final bundles. Moving to CSS modules and running a css class minifier and deduplicator is the best thing you can do if you work in a project where performance is critical. Anecdotical, but the best improvement I've achieved doing this is shaving off ~30% of our final bundles, gzipped!)