Tailwind CSS not applying styles - css

I am currently building a react-express web app and today I ran into many bugs, The first issue was with Webpack-5. I solved it by downgrading the version to 4.0.3 but when I started the react-app, the CSS was not working so I thought it might be an error with Node JS version so I installed the latest version but that caused another bug so I installed the LTS 16.15.1 version but the CSS still did not work. So the next thing I did was reinstall tailwind but that still did not fix it. I don't receive any error messages in the console or in the terminal.
tailwind.config.js
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
postcss.config.js
export const plugins = {
tailwindcss: {},
autoprefixer: {},
};
package.json
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"sass": "^1.52.1",
"tailwindcss": "^3.1.3",
"typescript": "^4.7.3"
}
Here is the link to the project if that helps in any way.

I had the same issue, the solution for me was in the content array in the tailwind.config.json where I specified the path to the folder where I what the styles to get applied
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./page-section/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
primary: "#366B45"
},
fontFamily: {
sans: ["Inter", "sans-serif"],
},
},
},
plugins: [],
};

I finally fixed the issue by following this: https://www.smashingmagazine.com/2020/02/tailwindcss-react-project/.
But am still not sure why it stopped working suddenly. The only problem with this solution is that on npm start it builds the CSS and outputs it to another file. The problem with that is that I have to restart the server everytime I make a change to the CSS.

Try to add the following in the index.css file
#tailwind base;
#tailwind components;
#tailwind utilities;

Related

Tailwind with Next.js Error: Expected a backslash preceding the semicolon

I've been struggling with this one for quite a while. Everything was working perfectly and suddenly started failing to compile.
When running npm run dev I get this error:
error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[2]!./styles/global.css
Error: Expected a backslash preceding the semicolon.
at resolveMatches.next ()
at Function.from ()
at runMicrotasks ()
Import trace for requested module:
./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[2]!./styles/global.css
./styles/global.css
The tailwind installation was done following this guide from their website: https://tailwindcss.com/docs/guides/nextjs
I have not changed anything after that.
My global.css only contains the three lines needed by tailwind:
#tailwind base;
#tailwind components;
#tailwind utilities;
package.json:
{
"name": "skillsboardai",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#headlessui/react": "^1.7.8",
"#heroicons/react": "^2.0.14",
"i18next": "^22.4.9",
"i18next-browser-languagedetector": "^7.0.1",
"i18next-http-backend": "^2.1.1",
"next": "^13.1.6",
"next-i18next": "^13.0.3",
"openai": "^3.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^12.1.4"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.4"
}
}
My tailwind.config.js:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
}
My postcss.config.js:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
And lastly, my _app.js imports the CSS
import React from 'react'
import '../styles/global.css'
import { appWithTranslation } from 'next-i18next';
function App({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(App);
I've seen similar posts, but they are related to other frameworks so I wanted to open this thread in case there is any specific actions to take within Next.js.
I am out of ideas and is frustrating, as it was working before.
I have tried:
Removing tailwind: all works fine, but no tailwind of course
Emptying global.css: all works fine, but no tailwind of course
Removing all tailwind classes in my components: did not work
Deleting .next folder and regenerating it: does not work
Deleting also the node_modules and re installing them: does not work
Even went back to my last known-to work commit: DOES NOT WORK EITHER!
I found the solution!
So in one of my components a div had the className [&:not(:focus-visible)]:focus:outline-none
I have no idea why it had that format, most likely some copied class from the web.
Anyway, remove that class, problem solved. Too bad the error given is so vague.

How can i apply tailwind css in app folder in Next 13

Tailwind CSS is not applying to the app folder in the next.js v13, but it is working on the Pages and Components folder.
In the tailwind.config file, I have added
However, no CSS is being applied to components in app folder!
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./app/**/*.{js,ts,jsx,tsx}",
],
try to check the following: (works for me)
in next.config.js
set experimental.appDir: true to enable app directory feature
const nextConfig = {
experimental: {
appDir: true,
},
}
in tailwind.config.js
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
...
}
in ./app/globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
in ./app/layout.tsx
import css in layout => works fine
import css in page => not working
import './globals.css';
...
Using tailwindcss with Nextjs 13 and Turbopack
Update dependencies
npm install -D tailwindcss postcss autoprefixer concurrently
npx tailwindcss init -p
Configuring tailwind.config.js
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}", // Note the addition of the `app` directory.
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Configuring next.config.js
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
experimental: {
appDir: true,
},
}
module.exports = nextConfig
Update package.json
// ...
"scripts": {
"dev": "concurrently \"next dev --turbo\" \"tailwindcss --input ./styles/input.css --output ./styles/output.css --watch\"",
"build": "tailwindcss ./styles/input.css --output ./styles/output.css && next build",
"start": "next start",
"lint": "next lint"
},
// ...
Create ./styles/input.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Create empty ./styles/output.css file
Create ./app/layout.tsx
import "../styles/output.css";
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Add styles to ./app/page.tsx
export default function Home() {
return (
<h1 className="m-12 text-4xl text-red-600">
Welcome to NextJS 13 with tailwindcss and turbopack
</h1>
);
}
Run project
npm run dev
References:
Tailwind CSS
Use Turbopack with TailwindCSS and Nextjs 13 today
I think #lorekkusu is right, but missed something.
Assuming I'm working on /app/blog/page.tsx, globals.css will be required to imported again, despite it was imported at /app/layout.tsx
import '../globals.css' //at /app/blog/page.tsx
Ah... Figured out the issue to resolve my comment.
In my case, I had to do an additional update to my next config because I am using Turborepo.
In NextJS 12, the following was what I had in my next.config.js
const withTM = require("next-transpile-modules")(["ui"]);
module.exports = withTM({
reactStrictMode: true,
experimental: { appDir: true }
});
However, I realized by spinning up a new turborepo from latest, that the way you transpile code has changed. This now also needs to be declared in the experimental block.
module.exports = {
reactStrictMode: true,
experimental: {
transpilePackages: ["ui"],
appDir: true
}
};
Once you do this, along with the listed steps in the nextjs documentation, you should be able to use tailwind in Next + Turborepo :)
Had the same problem.
I moved globals.css from /app to /styles, and then import in app/layout.tsx.
Now works fine.
You can follow this step:
Inside the root layout (app/layout.js), import the global.css stylesheet to apply the styles to every route in your application.
If you've selected the "use /src" option while installing nextjs then you need to have your tailwind.config.js configured as such:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/app/**/*.{js,ts,jsx,tsx}',
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
}
Remember the moment you change your folder structure to /app style in Nextjs project you need to add this line into your
in tailwind.config.js
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}", // <-------------------
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
...
}
After that check following:
in next.config.js
const nextConfig = {
experimental: {
appDir: true,
},
}
in globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
And finally, where ever you are importing the globals.css
do it like:
import './globals.css';
You can refer to this documentation here.
Next config should be experimental
const nextConfig = {
reactStrictMode: true,
experimental: {
appDir: true,
},
}
You need to be add app directory for tailwind
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [
require('tailwind-scrollbar'),],
}
Globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Most important step
import '../styles/globals.css'
if you are migrating to next 13 your globals.css should be in app directory after adding it. You can import it by this:
import './globals.css';
You need to follow the four steps
Install Tailwind CSS
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Change the config to root path or prefix /src folder
/* /tailwind.config.js */
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/app/**/*.{js,ts,jsx,tsx}',
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
};
Apply the tailwind to globals css /src/app/globals.css
/* /src/app/globals.css */
#tailwind base;
#tailwind components;
#tailwind utilities;
Configure PostCSS config file /postcss.config.js
// /postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
In my case I was making the pages like
src/pages/blog.jsx
It did render but tailwind wasn't working.
Then after reading the [Pages and Layout] docs for the app directory i moved it to src/app/blog/page.jsx
and now it works :D

Tailwind css not getting included in project

I am using tailwind post CSS in my HTML, but classes are not applying.
I have installed all packages have linked CSS too.
tailwindconfigjs file
module.exports = {
content: ["*"],
theme: {
extend: {},
},
plugins: [],
}
Is there anything to change?

Tailwind css classes not showing in Storybook build

I am trying to build my storybook with tailwind css. When running build-storybook the components are rendered with the tailwind classes. Unfortunately, when I build storybook and run the create build storybook-static with npx http-server storybook-static the classes are not loaded into the stories and the components are displayed not styled.
This is a repro repo of my project:
https://gitlab.com/ens.evelyn.development/storybook-issue
This is my main.js :
const path = require('path')
module.exports = {
"stories": [
"../src/components/**/**/*.stories.mdx",
"../src/components/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
"#storybook/addon-actions",
"storybook-tailwind-dark-mode"
]}
My Projectstructure looks like this:
.storybook
src
components
subdir
Button
index.tsx
button.stories.js
styles
index.css (<-- tailwindcss file)
Any hints or advice is very appreciated.
UPDATE: My original answer could be useful to others, so I'll leave it for reference. However, in this case, the problem was in tailwind.config.js.
Change
purge: {
mode: 'all',
content: [
'./src/components/**/**/*.{ts, tsx}'
],
},
to
purge: ['./src/**/*.{js,jsx,ts,tsx}'],
ORIGINAL:
Just tested it out and storybook builds as expected for me. I think the key difference in our configurations is that I am not making changes to Storybook's webpack config in main.js. Rather, I am using #storybook/addon-postcss for postcss#^8 (required for tailwind#^2):
// main.js
module.exports = {
...
addons: [
...
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
],
};
I specify the necessary plugins in a postcss.config.js (in my project root):
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
It's also worth noting that I import Tailwind directly in Storybook's preview.js instead via my own css file:
// preview.js
import 'tailwindcss/tailwind.css';
export const parameters = {...}
Hopefully, making those changes will get Tailwind working for you.
For comparison (see comments below), here are the contents of my build storybook-static directory:
The above solutions will not work for Tailwind version > 3.0 because of JIT compiler.
Solution 1: Easy solution
in .storybook/preview.js file add this line to compile tailwind generated css files like this -
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
Here tailwindcss/tailwind.css is the tailwind css file. Look, important is I've to add !postcss-loader! to compile tailwind generated css.
You can add also your custom scss file like this if any -
import '!style-loader!css-loader!sass-loader!../src/scss/style.scss';
Here ../src/scss/style.scss is custom scss file.
For most of the people this will work in Tailwind version > 3.0 without any issue.
Solution 2: Kinda Hack solution
Create a custom styled element in preview page
import tailwindCss from '!style-loader!css-loader!postcss-loader!sass-loader!tailwindcss/tailwind.css';
const storybookStyles = document.createElement('style');
storybookStyles.innerHTML = tailwindCss;
document.body.appendChild(storybookStyles);
Hope, this will help for new Tailwind users who are working in Tailwind greater than v3.0.
I had a similar problem. My problem was solved by adding:
import "../src/index.css"; to .storybook/preview.js
The following configuration will enable so Tailwind generate CSS as new tailwind classes are added to the markup in dev mode (hot reload).
In summary, I don't think #storybook/addon-postcss works with Tailwind JIT and Storybook hot reload, and the workaround is to use the postcss-loader webpack loader.
Install these deps:
#storybook/builder-webpack5
#storybook/manager-webpack5
postcss-loader
webpack (must be version 5)
// .storybook/main.js
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
// {
// name: "#storybook/addon-postcss",
// options: {
// postcssLoaderOptions: {
// implementation: require("postcss"),
// },
// },
// },
],
framework: "#storybook/react",
core: {
builder: "webpack5",
},
webpackFinal: (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
// .storybook/preview.js
import "../styles/globals.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
if you using storybook with TSdx and tailwind css you should be able to import a CSS into components
To be able to import your CSS into components, you will need to tell
TSDX how to include it with your code. For that, you will need to
install rollup-plugin-postcss (as TSDX uses rollup).
Create a CSS file in your src directory which we will use in any
component in which we want to use Tailwind.
Alright, so now let's add rollup-plugin-postcss:
yarn add -D rollup-plugin-postcss
TSDX is fully customizable and you can add any rollup plugin, but be aware that it overrides the default behavior
Now you'll create a
tsdx.config.js
// tsdx.config.js
const postcss = require('rollup-plugin-postcss');
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
config: {
path: './postcss.config.js',
},
extensions: ['.css'],
minimize: true,
inject: {
insertAt: 'top',
},
})
);
return config;
},
};
This is giving a postCSS path, which tells it what files you want it to run on. The minimize key is to allow you to minimize the output. The most important key here is the "inject". you set it to "top" to tell postCSS where inside the of our page the CSS will be inserted. It's paramount for Tailwind as it needs to have the utmost priority of any other stylesheet.
Next, for part 2, you will create a tailwind.css (can be named anything else) file under the src directory and paste this in:
// src/tailwind.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Add the CSS import statement to your component
// src/Thing.tsx
import React, { FC, HTMLAttributes, ReactChild } from 'react';
// ! Add the CSS import statement !
import './tailwind.css`;
// ...
// we'll add some Tailwind classes on our components to test
export const Thing: FC<Props> = ({ children }) => {
return (
<div className="flex items-center justify-center w-5/6 m-auto text-2xl text-center text-pink-700 uppercase bg-blue-300 shadow-xl rounded-3xl">
{children || `the snozzberries taste like snozzberries`}
</div>
);
};
For those who are still having this problem and is using postcss >= 8, I suggest you to do as following.
Add this to tailwind.config.js
// eslint-disable-next-line #typescript-eslint/no-var-requires
const path = require("path")
module.exports = {
content: [path.join(__dirname, "./src/**/*.(js|jsx|ts|tsx)")],
theme: {
extend: {},
},
variants: {}
plugins: [],
}
Add this to preview.js
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css"
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
This has helped me fix the problem and I hope it can help you too
I couldn't work this out and the above answered didn't work for me, so I eventually just set my build-storybook script to run tailwind itself after the build. package.json scripts looked like this in the end:
"build-storybook": "build-storybook -s public && $(npm bin -g)/tailwindcss -i storybook-static/static/css/main.*.chunk.css -o storybook-static/static/css/main.*.chunk.css -m",
Bit of a mess, but $(npm bin -g)/ here uses my globally installed (npm i -g tailwindcss) version of tailwindcss as the version installed to the project wasn't working in builds for me.
-i and -o specifies the input and output files, and -m minifies the output.
I can foresee this causing problems if more than one CSS file gets built (maybe using storybook-static/static/css/**/*.css would work instead?), but this might help someone just get something working.
When you try to create a storybook while using Tailwind CSS, you will notice that the CSS is not being applied. There is a simple solution that has helped me.
Your preview.js should be like.
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
And you will need to add the following line in the preview.js to fix it.
// Add the below import line
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
However this will be a temporary fix.
To get this resolved completely, you will need to add the below mentioned package.
yarn add -D #storybook/addon-postcss
For reference, click here
How to add postcss
The solutions mentioned above worked but only partially.
I was facing 2 issues:
If I added new classes to stories then tailwind was not adding corresponding styles associated with the classes.
Hot reloading wasn't working.
Solution:
Add the path to the stories folder in the tailwind.config.js file.
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./stories/**/*.{js,ts,jsx,tsx}", //needed to make hot reload work with stories
],
theme: {},
plugins: [],
}

Vite does not build tailwind based on config

I created a new react-ts app using yarn create #vitejs/app my-app --template react-ts.
I installed tailwind using yarn add --dev tailwindcss#latest postcss#latest autoprefixer#latest.
I initialized tailwind: npx tailwindcss init -p.
I set from and to in postcss.config.js:
module.exports = {
from: 'src/styles/App.css',
to: 'src/styles/output.css',
plugins: {
tailwindcss: {},
autoprefixer: {}
}
}
I created a App.css file in src/styles:
#tailwind base;
#tailwind components;
#tailwind utilities;
According to https://vitejs.dev/guide/features.html#postcss, any valid postcss-load-config syntax is allowed. from and to seem to be allowed.
When I call yarn dev which essentially runs vite, my app is starting without build errors but tailwind output is not generated.
What am I doing wrong?
make sure your postcss.config.js file is in your app root directory
it solved my problem
tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
mode: 'jit',
purge: {
enabled: process.env.NODE_ENV === 'production',
// classes that are generated dynamically, e.g. `rounded-${size}` and must
// be kept
safeList: [],
content: [
'./index.html',
'./src/**/*.{vue,js,ts}',
// etc.
],
},
theme: {
extend: {
fontFamily: {
sans: ['Inter var', ...defaultTheme.fontFamily.sans],
},
},
},
}
In your vite.config.js, make sure to include Tailwind in your plugins.
plugins: [react(),tailwindcss()],
Also, you can import Tailwind with the following.
import tailwindcss from 'tailwindcss';
from and to are not required.
I had to update my import statement for the css file in main.tsx to point to src/styles/App.css which will cause vite to run postcss.
Maybe you are forget to fill content object in tailwind config
module.exports = {
content: ['./src/*.{js,jsx}', './src/**/*.{js,jsx}'],
theme: {
extend: {},
},
plugins: [],
}

Resources