So you need a CSS utility library?

Share this:

Let's define a CSS utility library as a stylesheet with many classes available to do small little one-off things. Like classes to adjust margin or padding. Classes to set colors. Classes to set specific layout properties. Classes for sizing. Utility libraries may approach these things in different ways, but seem to share that idea. Which, in essence, brings styling to the HTML level rather than the CSS level. The stylesheet becomes a dev dependency that you don't really touch.

Using ONLY a utility library vs. sprinkling in utilities

One of the ways you can use a utility library like the ones to follow as an add-on to whatever else you're doing with CSS. These projects tend to have different philosophies, and perhaps don't always encourage that, but of course, you can do whatever you want. You could call that sprinkling in a utility library, and you might end up with HTML like:

Forgive a little opinion-having here, but to me, this seems like something that will feel good in the moment, and then be regrettable later. Instead of having all styling done by your own named classes, styling information is now scattered. Some styling information applied directly in the HTML via the utility classes, and some styling is applied through your own naming conventions and CSS.

The other option is to go all in on a utility library, that way you've moved all styling information away from CSS and into HTML entirely. It's not a scattered system anymore.

I can't tell you if you'll love working with an all in utility library approach like this or not, but long-term, I imagine you'll be happier picking either all-in or not-at-all than a tweener approach.

This is one of the definitions of Atomic CSS

You can read about that here. You could call using a utility library to do all your styling a form of "static" atomic CSS. That's different from a "programatic" version, where you'd process markup like this:

Beard's most popular and polarizing feature is its helper classes. Many people feel utility classes like the ones that Beard generates for you leads to bloat and are just as bad as using inline styles. We've found that having a rich set of helper classes makes your projects easier to build, easier to reason, and more bulletproof.

<div class="main-content md-ph6 pv3 md-pv6">
<h2 class="tcg50 ft10 fw3 mb2 md-mb3">Tools</h2>
<p class="tcg50 ft5 fw3 mb4 lh2">Beard isn't packed full of every feature you might need, but it does come with a small set of mixins to make life easier.</p>
<h3 class="tcg50 ft8 fw3 mb2 md-mb3">appearance()</h3>
</div>

This thing doesn't even exist yet and they have more than 700 Twitter followers. That kind of thing convinces me there is a real desire for this stuff that shouldn't be ignored. We can get a peak at their promo site though:

Utility Libraries as Style Guides

As Marvel continues to grow, both as a product and a company, one challenge we are faced with is learning how to refine the Marvel brand identity and apply it cohesively to each of our products. We created this styleguide to act as a central location where we house a live inventory of UI components, brand guidelines, brand assets, code snippets, developer guidelines and more.

This is separate-but-related to the idea of CSS-in-JS

The tide in JavaScript has headed strongly toward components. Combining HTML and JavaScript has felt good to a lot of folks, so it's not terribly surprising to see styling start to come along for the ride. And it's not entirely just for the sake of it. There are understandable arguments for it, including things like the global nature of CSS leading toward conflicts and unintended side effects. If you can style things in such a way that never happens (which doesn't mean you need to give up on CSS entirely), I admit I can see the appeal.

This idea of styling components at the JavaScript level does seem to largely negate the need for utility libraries. Probably largely a one or the other kind of thing.

Love the last section of your article. I think we are coming to a convergence between the Atomic CSS approach and CSS-In-JS. That Unified Styling Language thing. Today’s version of CSS Zen Garden is a JSON Theme File passed across projects to control type, color and scale (BYO-Grid to scaffold it together).

Structurally I see major benefits to using some of these utilities but some features seem very regressive. If you find yourself wanting classes for almost every individual CSS property just go back to using inline styles (a little sarcasm). So, just write good CSS and HTML and most of these libraries won’t be needed.

I know it was a joke, but it’s worth mentioning that with the style classes, you get the benefit of browsers caching the stylesheets, and you don’t need to worry about the inline styles being hard to override. For responsive web design, you can use the classes as a mobile-first “base”, and then combine it with a stylesheet to use media queries to handle the larger sizes. It helps keep the size of the stylesheets (or sass partials) down so it’s easier to read.

This list and all the examples make me sick!
The purpose of having an external style sheet with classes that can be called in the html is to separate the concerns.
In the old times we were applying styles directly in the html, and that was bad because the styles were linked to the html, changing a style meant changing the html file, an opportunity to break something at anytime and you had to repeat yourself ever and ever in the HTML.
If you put classes in your html you should avoid this tight coupling but if your classes do just one thing (mt0, padding-left-30, …) it is exactly as if you were writing your styles directly in the html because if you want to change the style, say have a padding left of 20 pixels, you will have to change the class you are calling in your html, and this everywhere you need to change it!
If you have a class like ‘my-title’, you don’t need to change the html, but just the styles inside the class, and just once.

I would think if you’re creating and editing a website that is just plain HTML, and not preprocessing the HTML or using modules to output HTML then I could see Utilities being a nightmare, as you’d have to add or remove the classes over and over for any element, for example a long list that might need that styling.

Now if you are using an HTML preprocessor or modular system that outputs HTML, say like Pug or Haml, and you have items being looped or repeated, then you’re just editing one line of code which makes Utility classes very maintainable, and quite useful for the developer.

I’d say all in all it’s project dependent, like most techniques out there :)

In my experience, Chris is exactly right. I wouldn’t recommend this to someone who doesn’t have access to a templating library. These types of techniques just shift the complexity and logic to the templating layer.

That being said, I haven’t worked on a project where I didn’t have access to templating in many years, so this was the right route for me.

I’ve been using this method for about 3 years now and it makes life so much simpler. Html markup is less vague, l know exactly how my markup is being displayed. With a set number of rules (.p1, .p2, .p3, .p4 – padding), you get consistency throughout the design. It’s much easier to style on the fly, responsive styling is also much simpler too. Small tests are also quick to build.

I agree with others, these libraries work best when used with a templating engine. Being able to name a component by its filename brings back a bit of specificity which can get a bit lost by this method.

If you’re working with a team I recommend basscss as the classes are very readable and quick to pickup.

I find the more a project grows the less I have to open up the css file which is a very good sign. I’m not worried about removing any legacy code because they’re just single class utilities.

I also wrote my own utility library, with SCSS mixins. Basically every util class must have responsive variants ( example px-10 for padding in x-axis 10 pixels ) becomes px-10, px-s-10, px-m-10, px-l-10 and so on, depending on how many breakpoints do you have. It ends up with ton of CSS ( most of which is never used ) and pretty ugly markup.

I can totally understand the resistance to the Atomic CSS approach as it goes against what many people regard as best practices. However, as we move towards building modular systems the more the utility class approach begins to make some kind of sense. I think Adam Wathan says it best in this post: https://adamwathan.me/css-utility-classes-and-separation-of-concerns/

Yep that article by Adam Wathan is the only one that got me to think seriously about utility-class based CSS.

He acknowledges the issues with HTML being filled with horrible classes like the examples above and suggests ways this can be mitigated, giving you the benefits of semantic classes AND consistent utility classes.

Essentially he suggests you use the utility classes as building blocks for the larger semantic module classes. However the easiest way to do this is with LESS, and since we all use SASS these days it does require writing a mixin for each utility class (LESS lets you include any class as if it was a mixin).

On a personal note, i totally agree with every statement Adam Wathan has made in his article. He neatly explained his transition from using ‘content specific’ CSS class naming conventions to ultimately settle with a combination of “semantic and functional CSS”, i.e., start up your project with functional (utility) classes and build reusable semantic components on top of these classes as required. Mattan Ingram gave some deep insights on this topic in his above comment.

His article described a process what every experienced Front-end web developer would have gone through. Our developer community has already embraced a lot of changes in front-end web development over the past decade. I think that resistants should at least try out these methodologies once.

I look forward to his utility first CSS framework https://tailwindcss.com/ and more adoption of this “semantic and functional CSS” approach.

If it’s a JS heavy front end app, I think I rather see very small style sheets and proper use of utilities. My “current” thinking with this is that there is a common sense approach to this where you define colors, fonts etc in 1 place, include a utility class for common things like margins (as a simple example). Then a BEM stylesheet as needed for unique situtions,

That way, just by looking at the HTML, you don’t have to hunt through a hundred CSS files, or create a style that isn’t extremely scoped to modify the use of a button in 1 particular situation. I’m buying into atomic/utility classes more and more and I’m eagerly awaiting Adam’s (@adamwathan) up and coming CSS utility library!

I’ve been looking at Utility Based libraries for a couple of weeks now, and I could find it useful on a single project that we would have full control over, but the projects that give our users the ability to add in their own content via a CMS makes me think that we lose that control of Utilities for that particular situation.

Though, I suppose you might be able to get away with setting default classes for each or

tag that gets output from something like TinyMCE editor, that could work.

I really do want to try one of these on my next project, question is, with so many, how do I choose? haha

Thanks for sharing shed.css on the list! It’s been working well for us on TED.com

To those that are less-than-enthusiastic: I completely understand your initial resistance – I found myself in the same camp until I actually tried it. It will allow you to work faster and with more consistency.

I use the best of both worlds- I have strict React component-specific styles, but also a file with a few classes for frequently-copied sets of properties. But rather than putting the utility classes in the markup, I use SASS @extend to utilize them straight in my main styles. This way everything stays in one place and I can see the full story of where a component’s styles are coming from.

My very favorite set of CSS utilities is SUIT CSS. I love that each package is very lean, installable on its own and customizable via custom properties. I also like its verbose, self-explanatory class names.

I really like SUIT CSS – it actually pushed me down this road. I found myself using SUIT classes for everything I possibly could and would be disappointed when I had to stray from them. I wrote many SUIT components that I would publish and reuse in my projects. Eventually I was using utility classes for nearly everything, and decided to go the full utility class route.

I then found writing long utility class names over and over again to be a pain, but I found tachyons to be a little too terse and difficult to parse.

During one of our front-end hangouts at TED, we decided to come up with a syntax that served our needs – reliable, predictable, and short.

shed.css is the result. We seek to shorten css properties wherever possible. When there’s a conflict, the “more frequently used (this is completely anecdotal)” properties get the shorter alias. This means:

f:r === 'float: right'
flx-g:1 === 'flex-grow: 1'

We’ve found that the gains in productivity outweigh the loss in ramp-up while getting used to them

A lot of these atomic CSS utility libraries are so split up that the class names become a new shorthand syntax for CSS, so you kind of get to learn CSS again, by learning all the shorthands for the various property-value pairs. And long, barely decipherable lists of class names are neither aesthetically pleasing nor very developer friendly – unless you are the developer of the utility library yourself. Add responsive design and you at least triple the number of classes.

The previously mentioned article has an intriguing idea however: utility-first CSS, where you start out with utility classes and create OOCSS abstractions as needed.

Some CSS-in-JS solutions like Styletron use atomic class names under the hood, but neatly abstracted away so that the developer doesn’t need to work with class names at all.

Chris, I’ve explored nearly every library you mention here. One of my favorites was probably Tachyons (mainly for the community and early adoption), but I wanted to ask: have you explored Elm? Here’s a great resource if you haven’t read a ton about it. Thanks!

When using, or thinking of using, a CSS Utility Library, what type of projects are you working on? As some have mentioned, this certainly seems much more usable on a modular, component based development approach.

How would you see this working in crappy e-commerce platforms (Hybris, Demandware, etc) for larger teams of devs?

My approach at the moment is to style individual elements and components using BEM (even if I write css-in-js, I still use BEM’s naming conventions).

If its css-in-js I put all of the styles inside the components .js file, and if there is no .js wizardry involved I just create a single ‘css like’ file corresponding to a component e.g ‘user-card.sss’.

That way If I need to change anything inside a component there is always a single place where I need to go.

On the other hand I define utill classes as needed for the layout and spacing between elements.

I realized the need for a functional/utility library already 2 years ago, and I started developing my own, slowly evolving it project after project.
Some of the examples presented here are extreme, for example: <h2 class="tcg50 ft10 fw3 mb2 md-mb3">Tools</h2>. Classes don’t have to be cryptic. Writing marge-bottom-xl instead of mb-xl isn’t going to make such a difference size-wise, but it will make a lot of difference readability-wise. I plan to open-source my utility soon.
In general though, we definitely need utility classes. The key to less CSS problems is writing less/abstracting more CSS.

In my humble experience, utility classes always bring more problems than expected.
In a responsive website, utility classes tend to get overwritten more than it should. It brings many questions regarding the workflow, and I agree there is enough substance for it to be discussed, however, in real life, these utility classes often give more constraints than anything else. And like many here, I’d rather organise my CSS well than bombarding my HTML with non-semantic classes, making maintenance harder in my pov.

Adam’s article is interesting but I find his articulation a bit light when it comes to the shift he made. There is nothing wrong with a “content-agnostic component” and this is very opinionated from him in my opinion. And by the way, isn’t that what he does by setting up a full CSS lib with utility classes? ie: .mar-r-sm {margin-right: 1rem;} . I’m not convinced at all by his argumentations even if it is smartly written and some points opens discussions easily.

Perhaps someone has already mentioned this, but the practice of using utility classes does not scale very well or is maintainable in the long run. In other words, I would be horrified to see twenty CSS classes for one HTML element.

The strategy that works best for me is to:
1) Use a preprocessor
2) Write my utility classes as mixins
3) Leveraging those mixins, I can create classes that make sense at first glance. Either using SMACSS, BEM or some other naming convention.

We recently re-did a huge site. We wanted to reduce the need for one-off css files and in-page css so we made the base css nice and simple – and readable which makes it easy to remember.

Something like <h2 class="uppercase pad-top condensed"> gives you a lot of flexibility without having to learn a whole new language. And you know pretty much exactly what that header is going to look like.

I have had to do very little additional CSS for this site and the team’s efficiency is much higher than when we had rogue styles all over the place.

Although, when you need to take on a new team member, they now need to learn all the utility class names that are being used by the system of choice.

Sure, it’s easy to fathom what “uppercase pad-top condensed” will do. But how would one know to could do it? It’s already known how to change the appearance of that h2 within the CSS – and if properly scoped and modularised any changes shouldn’t do anything bad.

I’m not against utility classes but I honestly cannot see how utility classes of this nature can do anything but add to the training/on-boarding requirements for a new developer. They already know regular CSS and how to use it.

Would the solution not be to work on the modularity/scoping of the CSS components to prevent “rogue styles” rather than add a whole bunch of new classes that need memorising?

@Pete : A new team member either has to learn the utility classes or navigate a huge CSS codebase and try to figure out what nav-menu-wrapper does in comparison with nav-menu and nav-menu-container.. If you’d try it out you’d realize the first one is much simpler.

The point is that though – and I think much of the scepticism is because of that – having one universal way of adding a margin to an element, ensures that once the existence of that utility class (or class-mixin) is known to developers, you avoid a whole load of code duplication and repetition Front-end Developers tend to do when CSS gets beyond a certain threshold, simply because it’s humanly impossible to go through the project and analyze / abstract classes on the go.

I go through a lot of code reviews as part of my job, and the one thing I see all the time is patterns which repeat themselves, unnecessary CSS properties and things that could be abstracted.

Functional CSS and Utility Libraries solve that issue once and for all.

Has there been any discussion of minification of these longer classes names? Since we minify our CSS and JS, what if a preprocessor scanned the HTML, found these long slew of class names, created a minified name in a production HTML file, as well as adding the created minified class (with styles) to the minified CSS. I’m guessing we could also remove unused styles from the minified CSS since we’re scanning the HTML for class names.

Thank you Chris for sharing this and specially to all for the comments, my mind is thinking and thinking as I use always different approaches in my projects always looking for the one, the only one, the unique and the final most useful approach for styling. This reading leading me to a related question: Someone here knows a tool that remove UNUSED CSS classes from a CSS file or files, I mean given a group of html files it check the CSS files and remove the classes you don’t use in any of them?

Yeah, lets just wait a bit for web components to be widely supported (or start using them now with a few quirks), write regular CSS and stop this nonsense. Or use BEM with Stylus/SASS in the meantime.

Some of this nonsense comes from people that don’t understand how to use a proper naming convention / structure for CSS. And it may be in part because of their backend background or just taking in blindly “best practices” without testing them in a big project.

From my experience BEM is suited for most purposes. I mean, really, CSS size/overwrites/etc. are not a concern if you plan your project properly and develop all components first. Most teams start developing page-by-page without analysing all design files, plan structure and develop components first.

Every component should have its own file, and is independent from the structure. This is the hard part where most coders mess it up.

The first weeks there will be little visible progress. Afterwards, developing just takes off. This first weeks are very stressful for the PM and client who wants to see “something”.

Having these kind of classes c:black f:2 t-t:u p:1 just for the sake of abstracting
is just insane. I have to learn another “language” within CSS just to understand what they mean. Why would you do that? Take this project to another team and they will have to re-learn this all over again. It just doesn’t make sense.

@Zeno : I doubt you’ve had exposure to real life big projects with actual real life product owners and designers, then you’d know it’s unrealistic to expect fully pre-complete designs on which you can do the analysis you mention. Sad, but true. With functional CSS you can be really agile and flexible, and efficient.

@George you mean really agile and flexible like you are with plain CSS if you got it right?

The sad truth is, people complain about CSS shortcomings and try to make it the way they expected it to work, rather than using the strength of it. If you avoid the cascade and specifity you’ve almost destroyd the most benefits of CSS. I do not know how you structure your projects, but I want my components to use the cascade and maybe look different dependent on their position in the DOM.

“Having these kind of classes c:black f:2 t-t:u p:1 just for the sake of abstracting is just insane.”

It isn’t “just for the sake of abstracting, and to treat it as such is an unfair characterization. The effect actually removes abstraction from the CSS layer. It deals in concrete representational qualities rather than business or domain-specific ideas.

Rather than dealing with abstraction in your CSS and Markup, you now just deal with it in your markup. Your CSS becomes a set of constraints rather than an addition layer of indirection.

“I have to learn another “language” within CSS”

as far as naming goes, the shorthands mimic css properties closely. We opted for shorthand rather than longhand because the long-term gains in productivity and speed outweighed the short-term learning curve.

“Take this project to another team and they will have to re-learn this all over again”

I responded to a similar worry in another thread, but it bears repeating:

Bringing on a new dev in “normal” css situations requires them to learn:

Really? I could just inspect the element with headline-primary class and see what values it has. How would you inspect elements with your shortcut classes? You’ll never know what was intended, there is no inheritance, everything comes directly from those “functional” (I would call it rather inline CSS) classes.

You’ll notice than my initial feeling towards the concept – like most of us – was disgust. I find very interesting that most of the comments on this post are right in line with what we all think before we actually try to use utility classes on a project and see the benefits.

For the record, I have joined a new company a month ago. In the last 4 weeks, I have been ramping up with the CSS codebase and I am not anywhere near confident that I know how to use it / extend it yet.

The CSS is very well organised by very smart developers. It’s not about that. It’s about the immense cognitive load that comes with learning a new vocabulary, a new system. It’s overwhelming.

I find myself scoping out my new CSS to a specific class, so I don’t “break” other pages while I learn the system. I am instantly creating technical debt, on my first assignment. :/

With something like Tachyons, I feel strongly confident I can onboard anyone within 3-4 days.

Great to see this approach to front-end styling picking up speed in the recent months. As a developer, I started out using semantic class names in CSS. After I made the paradigm shift to functional CSS and utility classes, I’ve never looked back. It speeds up development time by a mile.

This was built after realising that I was writing the same utility classes over and over again for each project. Now, I barely write any CSS at all. Just configure my breakpoints, typography, sizing, colors, etc in scarab-carapace, and it builds a functional CSS stylesheet programmatically.

👋

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress and powered up by Jetpack. It is made possible through sponsorships from products and services we like.