shlogg · Early preview
Ramu Narasinga @karthik-m22

Understanding Tailwind CSS WithAlpha Utility Function Explained

Tailwind CSS's `withAlpha` utility function applies opacity to a color using `color-mix`. It converts numeric alpha values to percentages and ensures they're in the correct format for `color-mix()`.

In this article, we analyse withAlpha utitlity function in Tailwind CSS source code.

/**
 * Apply opacity to a color using `color-mix`.
 */
export function withAlpha(value: string, alpha: string): string {
  if (alpha === null) return value
  // Convert numeric values (like `0.5`) to percentages (like `50%`) so they
  // work properly with `color-mix`. Assume anything that isn't a number is
  // safe to pass through as-is, like `var(--my-opacity)`.
  let alphaAsNumber = Number(alpha)
  if (!Number.isNaN(alphaAsNumber)) {
    alpha = `${alphaAsNumber * 100}%`
  }
  // If the alpha value is a p...