tailwind-csstailwind-css-4

The bg-opacity-* utility no longer exists as of v4 - how could it still be created?


In some cases, it's useful to declare the bg-opacity value without using a modifier.

So instead of writing bg-sky-500/50, I'd prefer to use bg-sky-500 bg-opacity-50 in v4 as well.

However, it works in v3:

<script src="https://cdn.tailwindcss.com"></script>

<div class="size-16 bg-sky-500"></div>
<div class="size-16 bg-sky-500 bg-opacity-50"></div>

but no longer in v4:

<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>

<div class="size-16 bg-sky-500"></div>
<div class="size-16 bg-sky-500 bg-opacity-50"></div>


Solution

  • Exactly - due to the use of modifiers, in most cases there's no longer a need for a separate bg-opacity-* utility.

    Check out the new guidelines: modifier (recommended)

    Use opacity modifiers like bg-black/50

    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    
    <div class="size-16 bg-sky-500"></div>
    <div class="size-16 bg-sky-500/50"></div>

    Note: If you're just looking for an alternative for bg-opacity, this bg-color/opacity e.g. bg-sky-500/50 might work for you as well - and you may not need the exact old bg-opacity utility.

    Restoring legacy bg-opacity-* in a specific use case

    However, if you still need it, you can reintroduce it with the following adjustments:

    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <style type="text/tailwindcss">
    @utility bg-opacity-* {
      --background-opacity: calc(100% - --value(integer) * 1%);
    }
    
    @utility bg-* {
      background-color: color-mix(in oklab, --value(--color-*, [*]) var(--background-opacity, 100%), transparent);
    }
    </style>
    
    <div class="size-16 bg-sky-500"></div>
    <div class="size-16 bg-sky-500 bg-opacity-50"></div>

    Note: When modifying the bg-* utility, there's no need for an @supports check or a fallback value - TailwindCSS still handles that for you.