reactjsnext.jstailwind-css

Why are dynamically generated Tailwind CSS classes not applying in Next.js, while static classes are working fine?


I'm building a page using Next.js and Tailwind CSS, where I am dynamically generating some classes based on JavaScript variables. Some classes, like padding and border styles, are working as expected, but Tailwind CSS classes for rounded corners (such as rounded-t-xl and rounded-b-xl) are not being applied, even though the classes are correctly generated in the code.

Here is the code I'm using:

export default function Page() {

  const padding = 'p-2';
  const borderClass = 'border border-gray-800';
  const round = 'xl';
  const roundClass = 'rounded-' + round;
  const roundClassT = 'rounded-t-' + round;
  const roundclassB = 'rounded-b-' + round;

  return (
    <div className={`mt-16 w-96 h-96  mx-auto my-auto flex flex-col ${borderClass} ${roundClass}`}>
      <div className={` w-full ${padding} bg-gray-400 ${roundClassT} `}>
        Header
      </div>
      <div className="flex-grow p-2">
        roundClassT: {roundClassT} <br />
        roundclassB: {roundclassB}
      </div>
      <div className={`w-full ${padding} bg-gray-400 ${roundclassB}`}>
        Footer
      </div>
    </div>
  );
}

Issue:

Expected Behavior:

Environment:

I've ensured that the class names are correct, but they don't seem to be applied, while other Tailwind CSS utilities like padding and borders work fine.

Has anyone encountered a similar issue? Any guidance would be appreciated!


Solution

  • In context of next.js, i found the solution. We can use Tailwind's safelist feature (in tailwind.config.js) to ensure that dynamic classes are included in the build.

    Example:

    module.exports = {
      content: [
        "./src/**/*.{js,ts,jsx,tsx}",
        // include other paths as necessary
      ],
      safelist: [
        "rounded-t-xl",
        "rounded-b-xl",
        "rounded-xl",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    };