DEV Community

Discussion on: How and Why I Avoid Magic Numbers in CSS

aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

I've actually run into this situation myself before, and I have to disagree. This is one of those cases where refactoring actually makes things worse. Not every instance of a magic number is necessarily a code smell.

I would much prefer to see 4px and 2px all over the place in your code instead of --page-padding and --gap-width. Why? Two key reasons:

  1. It's easier to immediately parse. I don't have to track down those properties and remind myself of what they do, and then mentally substitute them everywhere they're used.

  2. Any time you run into a situation where many other things need 8px, 16px, and so on, you'll find yourself defining really obtuse and illegible calcs that try to manipulate page-padding or whatever other custom properties you're using.

The one notable downside to using raw/magic dimensions is that if you decide to make things more cluttered or more spread out in the future, you'll have to replace every instance of those numbers with the updated versions. But that is not something you should run into frequently (if it is, then you haven't devoted enough time to wireframing).

You say:

that's much easier to reason about and the intent of the code is clearer.

But how?

padding: 0 var(--page-padding);
grid-gap: calc(var(--page-padding) / 2);

I look at this and think "Huh, okay, now what's page padding?" A little repetition won't hurt your code. In fact, compare that to this:

padding: 0 4px;
grid-gap: 2px;

Much simpler and easier to read.

This scenario is analogous to the one of unnecessary inheritance in OOP development. The problem you usually run into there is trying to extend something for reuse (to avoid code duplication) where it simply isn't appropriate to do so. You usually end up shooting yourself in the foot.

mpuckett profile image
Michael Puckett Author • Edited on

That’s a really great alternative take! Agree that it can go the opposite direction and hinder readability if you go overboard.

Instead of creating multiple calc functions for various paddings/gaps in the code, I prefer having a standardized set of padding variables. That usually keeps things simple, but requires buy-in from the designer.

In the article I linked there’s a better use for calc, something like: calc(var(--standard-padding) - 1px) for rare exceptions.

Also it may be true that upon initial glance you know fewer specifics about the code (“exactly which number pixels do I push?”), the original intent has been translated into the code, which should make the overall process of making changes easier to reason about.

Appreciate your response!