I love utility CSS. It means I write CSS once, and change it rarely. I can quickly and easily add/change pages, and can often read a chunk of markup and know what something will look like. text-right font-bold is more obvious to me than nav_item--inner.

But a common complaint is “it’s like inline styles”. This seems based purely on appearances, rather than actual function. Looking similar doesn’t mean they are the same.

People rarely ask “why is that bad?”. What is actually wrong with inline styles? Does any of that apply to functional CSS? Let’s find out!

Inline styles don’t allow media queries

This is a huge reason to not use inline styles. And a valid one. It does not apply at all to functional CSS! Utility classes in bootstrap, tailwind, and others have classes with media queries.

You can use .p-md-2 to only add padding on medium-and-larger screens. Or d-sm-noneto hide stuff on small screens.

Inline styles cannot be easily changed

For testing quick changes in devtools, or changing a style project-wide. Inline styles requires a full text find/replace. Using CSS does not. You want to be careful to not end up with .text-red { color: blue }. But this can be avoided by naming things properly in the first place. If you change your primary color, the one-line CSS change for text-primary is easier than replacing every color attribute.

Maintenance is harder

Similar to the previous point; with correct names this shouldn’t affect functional styles. There are cases where you’ll still need a find/replace (i.e. if you decide labels shouldn’t be bold). In this case component styles are simpler, as you just update the label.

Separation of Concerns is another popular-but-misguided argument against util classes. Splitting unrelated components or modules into different files is how you separate concerns. Putting related code far apart because they have different file extensions is not.

Performance blah blah

Please measure before using this as an argument. There may at some point be a performance impact. But this is not your bottleneck yet. If you are serving many MB of HTML without gzip, this may come into play. If you get to that stage you have other problems.

I think a lot of this comes from people opening devtools and seeing so much markup. But browsers don’t really mind this. They are pretty good at parsing HTML. Don’t optimize for devtools users.

Additionally, you can easily strip out unused classes with a tool like purifycss. This leaves you with a pretty minimal set of styles + markup.

References

Leave a comment