It isn't ideal to avoid it entirely: sometimes you need to calculate a value for some style rule, or test some condition in order to assign the right
But JS-based solutions aren't right for me, either. The reasons I don't like them are that they stack on more complexity in order get around a simple process we already know how to perfectly well.
I use Stylus as a CSS preprocessor, because I like the absolute minimalist syntax and the consistent grammar of its built-in functions, but there is absolutely no reason you couldn't use SASS, or LESS, or any other preprocessor that supports nesting. You may use no preprocessor at all.
You don't even need to nest your styles if you don't want to, but if you don't, you will need to repeat the component class name on every line by hand.
Assuming I am working on a React component called
DetailCard, my method is simply:
- Create a
- Make sure the Component's root element has
- Create a
- Make the outermost style
.DetailCard, and then nest all other styles inside it, like this:
.DetailCard background-color red h1 font-size xx-large color white ul margin-top 2.4rem
.The key thing is that all styles are contained in, and scoped by, a
classNamethat is tied uniquely to your component. This prevents the CSS from leaking into the global name space, at least in theory. If you have multiple components with the same name, that is a separate problem!
I'm of the opinion that trying to avoid global styles altogether is not worth the cost. It often leads to needlessly repeating the same styles over and over, because your strictly-scoped solution has kept you from reusing it. The C in CSS stands for Cascading, and you shouldn't be afraid of it.
Anyway, some CSS should be global, like reset or normalize, not to mention your site's typographical rules.