Unable to Utilize Custom Colors in Tailwind CSS within NextJS

I am currently experimenting with NextJs and Tailwinds CSS for a new project. However, I keep encountering an error when attempting to apply a custom background color:

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. Make sure that any `@import` statements are processed correctly before Tailwind CSS sees your CSS, as `@apply` can only be utilized 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

Answer №1

If you want to harness the power of the unique arbitrary value syntax (using square brackets), you must activate JIT mode and ensure you are running Tailwind version 2.1 or higher. By doing so, your CSS will be compiled dynamically, allowing you to utilize the square bracket syntax and step outside the limitations of your design system.

For more detailed information on JIT mode, check out the Tailwind documentation.

To activate JIT mode:

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

Answer №2

In an extended theme, you have the ability to directly access custom colors and variables. I have included my entire tailwind.config.js file for reference.

const defaultTheme = require('tailwindcss/defaultTheme');

module.exports = {
    // Configuration settings here
};

To use the variables defined in `tailwind.config.js`, make sure to set them in your base layer with their corresponding values (e.g., hex/rgb/hsl). Once imported into your root file (_app.js if using Next.js or index.js), they will be applied globally.

Non-variable colors like `text-olive-300` will display a color widget next to them, whereas CSS variables such as `text-secondary-0` will not.

./styles/base.css

@layer base {
    #__next {
        // Styles for __next element
    }

    :root {
        /* CSS variables definitions */
    }

    /* Other base styles */

}

I typically organize my CSS files by breaking them up into individual layers within a styles directory and then import them all into an `index.css` file which is further imported into the main project.

For example:

./styles/components.css

@layer components {
    .fit {
        // Styling for fit class
    }
}

./styles/utilities.css

@layer utilities {
    /* Utility classes and styles */
}

./styles/index.css

@import 'tailwindcss/base';
@import './base.css';

@import 'tailwindcss/components';
@import './components.css';

@import 'tailwindcss/utilities';
@import './utilities.css';

Lastly, ensure to import ./styles/index.css into the root of your application. For PostCSS configuration needed for this setup, check out the contents of postcss.config.js:

module.exports = {
    plugins: [
        'postcss-import',
        'tailwindcss',
        'postcss-nesting',
        'postcss-flexbugs-fixes',
        /* Additional plugins here */
    ]
};

Answer №3

Encountered an issue while using VsCode and devised a solution

Tailwind version 2.2.16 paired with NextJs version 12.0.4

  1. Include the code snippet below in your tailwind.config.js file
module.exports = {
  mode: 'jit'
}
  1. Create a new file named css_custom_data.json in your project directory and paste the provided code
    {
  "version": 1.1,
  "atDirectives": [
    {
      "name": "@tailwind",
      "description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
        }
      ]
    },
   // Additional directives here
  ]
}
  1. Navigate to settings.json in VsCode (cmd+,) and insert the following configuration
 "css.customData": ["./css_custom_data.json"]

Answer №4

When using Tailwind CSS, it is crucial to make sure that the tailwind.config.js file contains the appropriate folder paths for your project. This will prevent any issues with class compilation during the build process.

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: 'class',
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
    './src/views/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
    },
  },
  plugins: [],
}

In my situation,

  './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
  './src/components/**/*.{js,ts,jsx,tsx,mdx}',
  './src/app/**/*.{js,ts,jsx,tsx,mdx}',

these default folder paths were originally included. I had to manually add

'./src/views/**/*.{js,ts,jsx,tsx,mdx}',
for the views folder in order for Tailwind to compile classes appropriately within that directory.

I trust this information will prove beneficial :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a snag with the getStaticProps() function in my Next.js project

I encountered an issue with my Next.js project: Error: page / getStaticProps cannot be attached to a page's component and must be exported from the page. More information can be found here: https://nextjs.org/docs/messages/gssp-component-member I sim ...

React error management not functioning as anticipated

I'm having trouble handling errors in my React app. I've been trying to figure it out, but for some reason, it's not working as expected. Below is the code I am using: App.js import ErrorBoundary from "./Error"; import ChildCompon ...

Is the background image unable to fill up the entire screen?

I'm currently facing an issue with my webpage's background not covering the entire vertical space. Despite trying different solutions and referring to previous posts, I haven't been able to resolve it yet. Here is the relevant code: <div ...

Tips for resolving the issue of background images not appearing in React JS

Having trouble adding a background image to my page, but it's not showing up. I've attempted using inline styles for the background image, but it's still not working and my page remains empty. import React from 'react'; import Pro ...

Struggling with transferring form input data to a different file using JavaScript, Node.js, React.js, and Next.js

I've been struggling with writing form input to a separate file in JavaScript. I created a demo repo to showcase the issue I'm facing. Check it out here: https://github.com/projectmikey/projectmikey-cant-write-to-api-dir-stackoverflow Locally, t ...

Some characters are not compatible with the CSS writing-mode feature

There seems to be an issue with the CSS writing mode not applying correctly to the symbol '№'. Here is an example: <html> <head></head> <body> <p style="writing-mode: vertical-lr;"> Номер № ...

Consolidate radio group in Vuetify platform

I'm having trouble centering the v-radio-group. Here's my current setup: <v-container grid-list-md text-xs-center> <v-form ref="form"> <div v-if="question.question_type == 'YESNO' "> <v-radio-group ...

The cache of React query fails to persist after using queryClient.setQueryData

Why is React query not maintaining its cache after queryClient.setQueryData? It also appears to be not working on defaultOptions as shown below. I have been using the React query developer tool which indicates that the data is stored after an API call, but ...

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

Leverage information retrieved from API in a separate React component

Is there a way to fetch data from an API in one component and then access it in another component without having to re-fetch the data? For example, if I fetch some data and create a table in Tables.js, how can I use that same data in TableDetails.js withou ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

What could be the reason for the inconsistent resizing behavior of this DIV container?

Upon viewing this demo, it becomes evident that there is an outer DIV containing an inner DIV on the left side with two inner SPANS. The challenge lies in positioning the two SPANS next to the DIV. If a line break (BR) is used to separate them, the width o ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

My React app is facing challenges in production due to issues with webpack

To enhance my React application, I incorporated a Google Maps API key and a mail sending library. However, safeguarding sensitive information such as the API key and password is crucial, which cannot be stored in simple variables. To secure these sensitiv ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...

typescriptIs there a more efficient approach to typing optional values without a default value in

In my React application with TypeScript, I am using the following code to provide typed props: type ScheduleBoxContentProps = { desc: ReactNode, lottie: LottieProps, } & Partial<{className: string}>; I want the className prop to be optional ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

Having trouble fetching session data from the server side with next-auth in a Next.js application

Currently, I am encountering difficulty retrieving the session on the server side while implementing next-auth in a Next.js project. When utilizing the useSession hook on the client side, I can retrieve the session object successfully. However, attempts to ...

What other option can be used in place of white-space:nowrap?

When using a textarea with the CSS property white-space:nowrap, it successfully removes spaces but adds a horizontal scrollbar to the text. I want to avoid the horizontal scrollbar while also preventing scrolling using arrow keys when using overflow-x:hi ...