Lesson 13 +10 XP

Functions & Directives

Functions & Directives

Tailwind exposes custom directives (at-rules) and functions you can use in your CSS.

Directives

@import - inline import Tailwind itself:

@import "tailwindcss";

@theme - define design tokens (see the previous lesson).

@source - explicitly add source files not auto-detected:

@source "../node_modules/@my-company/ui-lib";

@utility - add a custom utility that works with variants:

@utility tab-4 {
  tab-size: 4;
}

@variant - apply a variant to styles in your CSS:

.my-element {
  background: white;
  @variant dark {
    background: black;
  }
}

@custom-variant - add a custom variant:

@custom-variant theme-midnight (&:where([data-theme="midnight"] *));

Now theme-midnight:bg-black works.

@apply - inline existing utilities into your own CSS:

.select2-dropdown {
  @apply rounded-b-lg shadow-md;
}

@reference - import your stylesheet for reference (Vue/Svelte style blocks) without duplicating CSS.

Functions

--alpha() - adjust color opacity:

.my-element {
  color: --alpha(var(--color-lime-300) / 50%);
}

--spacing() - generate a spacing value:

.my-element {
  margin: --spacing(4);
}

Compatibility (v3 → v4)

@config loads a legacy JS config, @plugin loads a legacy JS plugin, and theme() accesses theme values via dot notation. These exist only for v3 compatibility - prefer CSS variables.

TL;DR

  • @import "tailwindcss" boots the framework.
  • @theme, @utility, @variant, @custom-variant extend it.
  • @apply inlines utilities into custom CSS.
  • --alpha() and --spacing() are build-time functions.