csstailwind-csstailwind-css-4

How to use hsl() function in tailwind @theme directive


I'm trying to define color variant with css hsl() function within Tailwind 4 @theme directive but it doesn't apply :

@theme {
    /* Colors */
    --color-primary: #006fa0;

    /* Darken colors */
    --theme-color-primary-darken: hsl(from var(--color-primary) h s calc(l - 5));

    /* Lighten colors */
    --theme-color-primary-lighten: hsl(from var(--color-primary) h s calc(l - 5));
}

Darken and lighten colors variant are exactly the same as the original.

I've take a look at somes existings answers like how-to-use-hsl-custom-color-in-tailwind-in-react but they all said to use tailwind.config.js but Tailwind 4 has now a zero-config approach so I was wondering how can I achieve my colors variations directly within css file ?


Solution

  • You can also declare the darken and lighten colors under the --color-* namespace like this:

    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <style type="text/tailwindcss">
    @theme {
      /* Colors */
      --color-primary: #006fa0;
    
      /* Darken colors */
      --color-primary-darken: hsl(from var(--color-primary) h s calc(l - 5));
    
      /* Lighten colors */
      --color-primary-lighten: hsl(from var(--color-primary) h s calc(l + 5));
    }
    </style>
    
    <div class="w-full h-8 bg-primary text-white">primary</div>
    <div class="w-full h-8 bg-primary-darken text-white">primary-darken</div>
    <div class="w-full h-8 bg-primary-lighten text-white">primary-lighten</div>