skip to Main Content

In tailwind why does bg-[#5ad0a1] work, however assigning the hex to variable for example const color = '#5ad0a1'; then bg-[${color}] not work?

<span className={`inline-flex items-center rounded-md bg-[${color}] px-2 py-2 text-md font-base text-[${color}]`}>
 {params?.value}
 </span>

2

Answers


  1. Because Tailwind needs the actual color (#5ad0a1) to be able to parse the code to create the css. It does not convert it to html with javascript and then parse the code. So it never sees #5ad0a1 only ever ${color}

    So it is likely creating something like

    .bg-[${color}] {
      background-color: ${color};
    }
    

    What you can try is use css variables

    In your css add, or if you need it to be variables add the root css in your js.

    :root {
      --main-color: #5ad0a1;
    }
    

    Then in your class use

    bg-[var(--main-color)]
    
    Login or Signup to reply.
  2. From tailwind’s docs:

    The most important implication of how Tailwind extracts class names is
    that it will only find classes that exist as complete unbroken strings
    in your source files.

    If you use string interpolation or concatenate partial class names
    together, Tailwind will not find them and therefore will not generate
    the corresponding CSS:

    So this is wrong and tailwind wont find the classes:

    <span className={`bg-[${color}] text-[${color}]`}>
          {children}
    </span>
    

    The recommended way is to map your props to static class names:

    const colorVariants = {
      bg: "bg-[#5ad0a1]",
      text: "text-[#5ad0a1]"
    };
    
    return (
      <span
        className={`inline-flex items-center rounded-md ${colorVariants.bg} px-2 py-2 text-md font-base ${colorVariants.text}`}
      >
        Hii
      </span>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search