NextJS project has been created already with tailwind support so I didn’t set up it by myself
When I add className
on html element on component in pages/
folder it simply doesn’t work even thought Elements panel in DevTools shows that className
is present
I tried to add a component in src/app/
directory with tailwind classes and it works fine
I saw somewhere in answers for the same problem that probably path pages/ is not present in tailwind.config.js but it is added in my config
here is code:
UPD:
layout.tsx:
import './globals.css'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export const metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory.
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
// Or if using `src` directory:
'./src/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
}
globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
here is usage in pages/news/[category].tsx:
export default function ArticleListByCategory({ articles, category }: { articles: Article[], category: string }): JSX.Element {
return (
<>
<h1>Showing news for catgory <i>{category}</i></h1>
{
articles.map((article: Article) => (
<div key={article.id}>
///////
<h2 className="text-red-500">
{article.id} {article.title}
</h2>
<p>{article.description}</p>
<hr />
</div>
))
}
</>
)
}
and here is what I see on the site:
However, here is src/app/example route code:
src/app/example/page.tsx:
export default function Example(): JSX.Element {
return (
<>
<h1 className="text-red-500">Hello</h1>
</>
)
}
and here is result for /example/
2
Answers
Make sure you are importing
globals.css
in your layout.tsx file. This will ensure that tailwind gets applied to every layout and page across your website.Keep in mind that stylesheets applied to your RootLayout will apply to every single nested layout. If you would like to use separate stylesheets for separate layouts, you can use a mixture of Tailwindcss Layers and CSS modules to achieve this;
https://tailwindcss.com/docs/functions-and-directives
To get this
Please read this section
https://tailwindcss.com/docs/customizing-colors
If you want to use their different variants then you can do something like that
Now you can use it like that