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

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Prevent the onClick event in the parent container div from triggering when clicking on a child element

Having trouble with event bubbling and onClick functions within a card element. The card has a heart icon that triggers an onClick function to unlike the card, but it also triggers the onClick function for the entire card which leads to a different page wi ...

Utilizing a (helper) function within Redux

I am currently using react-native-router-flux along with react-redux and I believe this is the right place to ask my question. Please correct me if I'm mistaken. Within my application, I have an ActivityModal Container which I use to display a modal ...

Caution: The value supplied to Material-ui Autocomplete is not valid

Currently, I am working on a project using React and material-ui. While working with the Autocomplete component in my form submission, I encountered a warning. Following the basic approach provided in the documentation, here's what I tried: let Form ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Displaying the appropriate DIV element based on the value entered by the user

I am encountering some difficulties... I have an <input> field. Depending on the input, one of the various <div> elements should be displayed. For now, it's just a text (e.g. "Your plan contains less than 1500 kcal!"), but later, the div ...

Adjust text alignment of SVG elements using CSS

I am facing an issue where I am unable to change the x and y variables of Svg text tags using CSS. This should work as it does with Svg and . However, I am only able to make changes if I directly add the x and y positions in the HTML code. Html: <svg ...

Material UI - Clear all designs from the slate

Is it possible to completely override all default material-ui styles and implement your own custom style guide for components? This would involve removing all material-ui styles and starting fresh with customized html skeletons. Creating a new theme with m ...

Excessive API requests can occur when Redux dispatches an action multiple times

Utilizing the Jikan API for anime, my objective is to showcase promo thumbnails of new anime shows. This involves two separate API calls: one to retrieve the latest anime shows: export const get_new_anime = () => `${base_url}search/anime?q&order_b ...

Creating a horizontal alignment for social media icons

Need assistance with aligning my social icons horizontally. I initially tried floating them to the left or using inline-block, but it's not working as expected. Any help would be greatly appreciated. Thanks! <!-- Customizing Social Network Icons ...

A guide to integrating server-side rendering for Material UI's media queries in NextJs

I'm having trouble following the instructions for implementing Material UI's media queries because they are designed for a basic React application and I am working with NextJs. Specifically, I'm not sure where to place the code provided in t ...

The error "Prop does not exist on type 'PropsWithChildren'" occurs when attempting to dispatch an action with react-redux

When attempting to dispatch the action, I am encountering this error: The error message reads: Property 'fetch_feed_loc' does not exist on type 'PropsWithChildren<{ onSubmitForm: any; }>'. Another error states: Property &apos ...

children blocking clicks on their parents' divs

I previously asked a question about a parent div not responding to click events because its children were blocking it. Unfortunately, I couldn't recreate the issue without sharing a lot of code, which I didn't want to do. However, since I am stil ...

What are some creative methods to apply CSS styling to material-table in React?

I've spent several days searching for a solution without any luck. My project involves using material-table in React, and I am struggling to apply CSS styles to the headers (columns) and content (such as changing font size, adjusting width, and creati ...

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The server is unable to process the request sent by the browser or proxy. This error occurred in a Flask web application

Can someone guide me on troubleshooting this issue in Flask? I am still learning. Server running at (Press CTRL+C to exit) 127.0.0.1 - - [26/Jul/2020 11:19:45] "GET /predict HTTP/1.1" 500 - Traceback (most recent call last): raise exceptions. ...

What criteria do browsers follow to determine the specific colors to use for border styles like inset and outset?

When I set border: 1px outset blue; as the style for an element, the browser displays two distinct border colors: one for the top and left borders, and another for the bottom and right borders. li { border: 10px outset #0000FF; color: #FFF; ...

I'm struggling to incorporate the JQuery slideDown function into my code. Can someone lend a hand?

Why isn't the video div sliding down and displaying properly in the beginning? Any ideas on how to fix it? Here is the snippet of HTML code and JavaScript: <!DOCTYPE HTML> <html> <head> <title>Team Songs</title> <link ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

Utilize a button to apply styles to a Span element dynamically generated with JavaScript

I am attempting to spin a span generated using JavaScript when a button is clicked. The class is added to the span, but the spinning effect does not apply. <p>Click the button to create a SPAN element.</p> <button onclick="myFunction ...

Loss of styling is observed with jQuery's html() function

Here is the HTML code I am working with: <div class="myList"> <select> <option value="1">Item1</option> <option value="2">Item2</option> </select> </div> Everything looks great in terms of CS ...