Utility Classes 2019-10-25 on Kenneth Dodrill's blog

When I (and...probably most others) started learning web development, I started with HTML mainly because of its 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>

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>

Things are starting to become more convoluted. 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>

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 the 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.

    panel-title(slot='title') Announcements
    router-link(:to='{ name: "promo" }')
    panel-title(slot='title') Videos
        .button.mt-3.p-3.is-link.is-small.is-rounded View All

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.