Search code examples
cssreactjscolorsnext.jstailwind-css

NextJS - Not Able To Use Custom Colors In Tailwind CSS In


I'm trying to use NextJs with Tailwinds CSS to make a project. However, whenever I try to use a custom color for the background color it throws this error:

Failed to compile
./styles/globals.css:7:12
Syntax error: /Users/anishkunapareddy/Desktop/Projects/React/hulu-clone/styles/globals.css The `bg-[#06202A]` class does not exist. If you're sure that `bg-[#06202A]` exists, make sure that any `@import` statements are being properly processed before Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.

  5 | @layer base {
  6 |   body {
> 7 |     @apply bg-[#06202A] text-gray-300;
    |            ^
  8 |   }
  9 | }

Code

index.js

import Head from "next/head";
import Image from "next/image";
import Header from "../components/Header";

export default function Home() {
  return (
    <div>
      <Head>
        <title>Hulu 2.0</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      {/* Header */}
      <Header />

      {/* Nav */}

      {/* Results */}
    </div>
  );
}

tailwind.config.js

module.exports = {
  purge: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

globals.css

module.exports = {
  purge: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

System Info:

OS: macOS BigSur 11.3 Node Version: 16.2.0


Solution

  • In order to use the arbitrary value syntax (with the square brackets), you need to enable JIT mode and ensure you are on Tailwind 2.1 or greater. This will compile the CSS on-demand, which allows you to use the square bracket syntax and "break out" of your design system.

    See the Tailwind docs for more info on JIT mode.

    To enable JIT mode:

    // tailwind.config.js
    module.exports = {
      mode: 'jit', // add this
      purge: [
      // ...
      ],
      theme: {
        // ...
      }
      // ...
    }