Home > Software design >  Text color not changing using NextJS with Tailwind CSS
Text color not changing using NextJS with Tailwind CSS

Time:08-05

In my NextJS app I'm using an <h1> tag for the text and wrap it in a <div> but when I try to apply a color to the text, it doesn't work. I even added in my global.css but it throws an error.

    <div className="mt-2 flex justify-start items-center text-2xl font-bold text-gray-300">
        <Image 
            src={Logo}
            width={40}
            height={40}
        />
        <h1>some text here</h1>
    </div>

The code above does not throw an error, but it also doesn't apply the style to the text.

styles/global.css

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    @layer base{
        body{
            @apply bg-[#06202A] text-gray-300; 
        }
    }

Applying styles in the base layer (above) throws the following error.

.../styles/globals.css The text-gray-300 class does not exist. If text-gray-300 is a custom class, make sure it is defined within a @layer directive.

tailwind.config.js

@type {import('tailwindcss').Config} */
    module.exports = {
      mode: "jit",
      content: [
        "./pages/**/*.{js,ts,jsx,tsx}",
        "./components/**/*.{js,ts,jsx,tsx}",
      ],
      theme: {
        colors: {
          'main-bg-color': '#02172F',
          'text-gray-color': '#fff'
        },
        extend: {},
      },
      plugins: [],
    }

postcss.config.js

    module.exports = {
      plugins: {
        tailwindcss: {},
        autoprefixer: {},
      },
    }

Why is this not working?

CodePudding user response:

You are replacing the default colors with your new additions. To add colors, but keep the defaults, you should place your new colors within the extend property.

module.exports = {
  mode: "jit",
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      colors: {
        'main-bg-color': '#02172F',
        'text-gray-color': '#fff'
      },
    },
  },
  plugins: [],
}

Also, the mode setting is no longer needed in Tailwind 3.0 . If you're still using V2, I would recommend upgrading if possible. If you cannot upgrade for some reason, I would like to point out that the default color classes are different between Tailwind 2 and 3, and you will have to reference the correct version's docs for the proper color set.

  • Related