How to Use Tailwind CSS and SCSS in a React/Next.js Project

tailwind

Tailwind CSS and SCSS (Sass) are powerful tools for styling web applications, and integrating them into a Next.js project can enhance your development workflow. In this article, we’ll walk through the steps to seamlessly use Tailwind CSS with SCSS in a Next.js project, allowing you to leverage the benefits of both technologies.

Steps to Integrate Tailwind CSS and SCSS

Step 1: Install Next.js with Tailwind CSS

Begin by setting up your Next.js project with Tailwind CSS. You can do this by running the following commands:

npx create-next-app my-nextjs-project
cd my-nextjs-project
npm install tailwindcss

Step 2: Install PostCSS Plugins

Install two additional packages, postcss-import and postcss-nested, to enable SCSS support in your project:

npm install postcss-import postcss-nested

Step 3: Modify postcss.config.js

Update your postcss.config.js file to include the necessary plugins:

 

module.exports = {
plugins: {
"postcss-import": {}, // Line 1
"postcss-nested": {}, // Line 2
tailwindcss: {},
autoprefixer: {},
},
};

 

Step 4: Update Globals.css

Modify the first three lines of your globals.css file to import Tailwind CSS styles:

/* @tailwind base;
@tailwind components;
@tailwind utilities; */

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

 

Step 5: Create SCSS Styles File

Create an SCSS file (e.g., Home.scss) inside your components folder or a dedicated styles folder within it. Import this file into your globals.css:

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

/* Styles Import */
@import "../components/styles/Home.scss";

Ensure that the style import is at the top of your globals.css file, just below your Tailwind CSS imports.

Using Tailwind CSS with SCSS

Now, you can write nested CSS in your Home.scss file and use the classes anywhere in your project:

.home {
width: 100%;

   .red {
color: blue;
}
}

 

Additionally, you can use Tailwind CSS classes directly in your SCSS files:

.home {
@apply w-full bg-slate-300;

.red {
@apply text-red-500;
}
}

 

Conclusion

Integrating Tailwind CSS with SCSS in a Next.js project provides a powerful combination of utility-first styling and organized, feature-rich syntax. Follow the outlined steps to enhance your styling capabilities and streamline your development process. Experiment with the flexibility of Tailwind CSS and the structure of SCSS to create a robust and efficient styling workflow in your Next.js projects.

Leave a Reply