Utility Classes


CSS HTML Web Development

Why you shouldn’t always use utility classes.

When I (and…probably most others) started learning web development, I started with HTML mainly because of it’s easy to understand syntax. It’s very readable because the syntax basically defines the meaning of what you are typing.

Let me start off by saying that utility classes are not bad. I just feel like they are misused too often.

Consider this example: I have an element X that I am using in some framework (let’s say Bootstrap for now).

<div class="row">
    <div class="col-sm-4 col-md-6 col-lg-8">
        <button class=""></button>
    </div>
</div>

This is very simple, and is required because we are using things from the framework. Now let’s extend it some more to get it like how we want.

<div class="row mt-2 mb-4">
    <div class="col-sm-4 col-md-6 col-lg-8 mx-auto">
        <button class="btn btn-primary ml-2 mr-4 mt-2 mb-5 p-1"></button>
    </div>
</div>

Things are starting to become more convoluted. And then…we add more…

<div class="row mt-2 mb-4">
    <div class="col-sm-4 col-md-6 col-lg-8 mx-auto justify-content-center">
        <button class="btn btn-primary btn-small ml-2 mr-4 mt-2 mb-5 p-1 inline-flex text-secondary border-0"></button>
    </div>
</div>

Now imagine this on a much larger scale. Things just keep building and building…until everything doesn’t make sense. The HTML is unreadable. Does this really follow good coding standards? I personally don’t think so.

A good rule that I follow is that if I have 5 or more individual classes on an element (not including layout classes such as row or col from framework), I’ll make a class or id for it.

A second reason that this could be bad is that these classes are not descriptive to someone new to the code (or even someone revisiting the code…even yourself). If you instead make descriptive classes and / or ids for your elements, you can achieve simplicity AND practicality.

Things like pugjs can also get pretty ugly (if done incorrectly), but I think that’s ultimately personal preference.

div
  panel-head
    panel-title(slot='title') Announcements
  panel-body.p-4
    router-link(:to='{ name: "promo" }')
      .flex.items-center.mb-3.text-sm.font-bold
        i.far.fa-angle-double-left.mr-2
        span.cursor-pointer(class="hover:underline")
.flex-1.border-b.border-grey-lighter-safe
  panel-head.border-t
    panel-title(slot='title') Videos
  panel-body
    .flex.flex-col.px-4.py-3
      .flex-1
          i.fas.fa-play-circle.text-3xl.absolute
      .hidden.flex-shrink.text-center
        .button.mt-3.p-3.is-link.is-small.is-rounded View All
div

I hope that this post will remind you sometimes of possibly going back to keeping things simple and easily understood. Syntax sugar can be nice, but sometimes it is overkill and could lead to lots of noise.