Today I Learned - Rocky Kev

TIL no global styles

POSTED ON:

TAGS:

I was reading this The No-Nonsense Styling Method and I strongly disagree. But that's totally okay!

This really shows that there's no agreed-upon method everywhere for CSS.

Here's the advice:

Use locally scoped styling only

Global styles is the largest anti-pattern in CSS. Global classNames cause numerous maintenance nightmares; they break encapsulation and information hiding, cause poor readability and discoverability, and pollute the global namespace.

Locally scoped CSS is an approach to CSS that fixes the problem of global styles.

Locally scoped CSS can be implemented with one of several available technologies that encapsulates CSS so that it is only usable within one component. css-modules, for example, prefixes classNames at build time so they are only usable within the components that import them.

Why do I have a problem with this?

It's because right below that, he points out a exception:

One exception: it’s probably fine to use a framework like tailwindcss but only if you can enforce these utility classes are only used to build reusable components...

In other words, global styles is a 'anti-pattern' if your code sucks. That's really what it comes down to. Use locally scoped styling because your code sucks.

I'm not anti-locally scoped styling. I just think it's a hack, a really good hack. But a hack none-the-less.

Locally Scoped Styling is great if:

Stick with Global styles if:

And in the words of Linus Trovalds, "I'll never be cuddly but I can be more polite"

While I disagree with Ben, it's more important to call out these 'rules' as more 'rules of thumb' or opinions.

via The No-Nonsense Styling Method


Related TILs

Tagged:

TIL no global styles

Global styles is the largest **anti-pattern** in CSS --- strong DISAGREE.

TIL no global styles

Global styles is the largest **anti-pattern** in CSS --- strong DISAGREE.

TIL no global styles

Global styles is the largest **anti-pattern** in CSS --- strong DISAGREE.