CSS Utility Classes and "Separation of Concerns"(adamwathan.me)

over 6 years ago from Adam Wathan, Full-Stack Developer

  • Emre AvciEmre Avci, over 6 years ago

    Great write up! I have one concern though, what if you want to change let's say your card elements to have a different type of border radius. Then would you need to go through all your card elements in all your html templates and change their classes? I would rather create semantic classes by @extend'ing the utility classes (sort of like your .btn-purple example, but for all elements). That way you can have semantic classes in your html, while still getting to pick out of limited number of utility classes. This would also resolve the issues that might come up because of the order of the classes.

    0 points
    • Adam Wathan, over 6 years ago

      Thanks Emre!

      If I see a pattern repeating enough and I can confidently say to myself, "if I change one of these, I'm going to want to change all of them," I'll usually make a new class that serves as a higher level abstraction around that group of utilities. Card is a good example for sure.

      I prefer not to do this for everything though, only when I see patterns. Otherwise you end up with this giant ball of CSS that's super coupled to your particular project, and you have to constantly make new classes even for parts of your UI that are never repeated, so your CSS size will grow linearly with your project size, which is death for maintainability in my experience.

      I wouldn't use extend because it has a lot of nasty side effects on your source order, especially when a component tries to extend a utility, because it'll move that component definition to the same place in the stylesheet where the utility is defined, which means that component's styles may get precedence over other utility styles you might want to add as modifiers.

      Instead, use mixins. This is really easy in Less because any class can already be used as a mixin, but if you are using Sass, I would extract a mixin from a utility as soon as I wanted to reuse it, and use that mixin in both the component and the original utility, like:

      EDIT: Code samples don't turn out great here, so check out this gist instead:


      0 points
      • Emre AvciEmre Avci, over 6 years ago

        Hey Adam,

        Thanks for the great examples, I can see your point. I guess it also kinda depends on what kind of a project you are working on and with how many other people. Also LESS looks pretty good for something like this so I will give it a shot in my next project.

        All in all really eye-opener article, made me think about how I structure my CSS. Thanks for sharing.

        0 points