Custom spacing utilities with Tailwind V4

I’ve been experimenting more with Tailwind V4 recently, figuring out the best boilerplate config to suit my preferred workflow. This included setting up some custom utilities, inspired by the great work over at Every Layout.


One thing the Tailwind docs don’t make immediately clear is how to make functional utilities work with the default spacing scale without repeating those values in the @theme config.

The solution turns out to be simple. Wrap --value() inside --spacing().

Here’s an example of a custom functional utility for The Stack, which I use in my Tailwind config.

Firstly, we define the default stack value (in this case mt-4):

@utility stack {
  > * + * {
    @apply mt-4;
  }
}

Next, we use the --spacing() function inside a functional utility. This allows us to use the default spacing scale as well as any custom --spacing-* variables set up in the @theme:

@utility stack-* {
  > * + * {
    margin-top: --spacing(--value(number, --spacing-*));
  }
}

You can also allow arbitrary values by adding [*].

@utility stack-* {
  > * + * {
    margin-top: --spacing(--value(number, --spacing-*, [*]));
  }
}

Using the --spacing(--value(...)) pattern also means intellisense will suggest the default spacing values (e.g. 0, 0.5, 1, 1.5, …, 96) — just like with built-in spacing utilities such as mt-* or p-*. This makes your custom utilities just as editor-friendly as the defaults.

I hope you find this approach handy for your future projects.


Reference: