Back to Top

Tailwind implementation in Next.js

Updated 22 November 2024

Installing and using Tailwind CSS with Next.js

Create your project

To start creating some UI’s awesome first create a new Next.js project to use Tailwind CSS with it. if you don’t have one set up already and if you already created one move on to the next step.

The most common approach is to use Create Next App.

npx create-next-app@latest

after creating the project go inside the project directory and install Tailwind as instructed below:

Install Tailwind CSS

Next, Install tailwindcss too and add its peer dependencies via npm, and then run the init command to create both tailwind.config.js and postcss.config.js.

//For tailwind install
npm install -D tailwindcss postcss autoprefixer
//For config file
npx tailwindcss init -p

Configure your template paths

And then add the paths to all of your template files in your tailwind.config.js file.

Start your headless eCommerce
now.
Find out More
/** @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: [],
}

and if you are using the src directory add their path in the content as well:

"./src/**/*.{js,ts,jsx,tsx}",

Furthermore, like this, you can add any path in your config file to use tailwind in that directory.

Add the Tailwind directives to your CSS

Completed the above steps?

Then Move on to the next step finally, and add the @tailwind directives for each Tailwind’s layers to your globals.css file or any file in which you want to use Tailwind.

@tailwind base;
@tailwind components;
@tailwind utilities;

Start using Tailwind and create awesome designs

After all this finally, you are ready to use tailwind in your next.js project and make UI’s with responsiveness.

And lots of customization without creating lots of classes and without making your project bulky.

     <div className="max-w-sm px-8 py-8 mx-auto space-y-2 bg-white shadow-lg rounded-xl sm:py-4 sm:flex sm:items-center sm:space-y-0 sm:space-x-6">
        <Image
          src={PLACEHOLDER_IMG}
          width={80}
          height={80}
          alt="demo"
          className="rounded-full"
        />
        <div className="space-y-2 text-center sm:text-left">
          <div className="space-y-0.5">
            <p className="text-lg font-semibold text-black">Erin Lindford</p>
            <p className="font-medium text-slate-500">Software Engineer</p>
          </div>
          <button className="px-4 py-1 text-sm font-semibold text-purple-600 border border-purple-200 rounded-full hover:text-white hover:bg-purple-600 hover:border-transparent focus:outline-none focus:ring-2 focus:ring-purple-600 focus:ring-offset-2">
            Message
          </button>
        </div>
      </div>
name_card
Name Card

and if you want to use CSS in an external file:

.btn{
@apply text-purple-600 font-semibold rounded-full border border-purple-200 hover:text-white;
}

Why choose Tailwind over other CSS frameworks?

Tailwind CSS is a utility-first CSS framework developed to enable users to create applications faster, more modular, and easier.

You can use utility classes like text-[], font-[], and hover: to control the layout, color, spacing, typography, shadows.

And more to create a completely custom component design — without leaving your HTML or writing a single line of custom CSS only using tailwind.

Some benefits of using tailwindCss

There are many benefits of using the CSS framework Tailwind over other frameworks. Below are the major ones.

  • Write less or even no custom CSS Or without meaning fewer classes. With TailwindCss, you style elements by applying pre-defined reusable classes directly in your HTML. By using utility classes in this way, you can build custom designs without writing CSS.
  • And besides all of this tailwind provides tailwind.config file as well for custom CSS and arbitrary values as well for your custom value.
  • You keep CSS files small or even don’t need them. Without a framework like Tailwind, you have to keep writing CSS and then projects become bulky and have a large number of meaningless classes.
  • By using utilities like Tailwind’s grid and margin utilities, most styles are reusable so you rarely need to write or even no need to write new CSS and you can even create your desired classes through the Tailwind config file.
  • You can make safer changes. With the traditional approach, if you make any changes to CSS, you may have chances to break something across your site.
  • Unlike CSS, utility classes in your HTML are local. This means that you can change them without worrying about breaking or diminishing something else on your page or on your site.

Here are some Main Features of tailwind

Tailwind is a Utility-First Framework:

  • You aren’t wasting energy inventing new class names which may be meaningless. No more adding silly class names like outer-div just to be able to style something, and no more worrying over the perfect abstract or meaningful name for something that’s really just a flex container.
  • Your CSS stops growing and becomes reusable. Using the old approach of CSS, your CSS files get bigger every time you add a new feature. With utilities and predefined classes, everything is reusable so you rarely need to write new CSS.
  • Changes become safer and easier. CSS is global and you never know what you’re breaking when you make a change. Classes in your HTML are local, so you can change them without worrying about something else breaking.
  • And then finally, if you want to create your own classes no worries you can create them as well by your tailwind config file in this way:
module.exports = {
  theme: {
    screens: {
      xl: '1440px',
    },
    colors: {
      'blue': '#1fb6ff',
      'gray-light': '#d3dce6',
    },
    fontFamily: {
      sans: ['Graphik', 'sans-serif'],
    },
    extend: {
      spacing: {
        '144': '36rem',
      },
    }
  }
}

Tailwind makes design responsive

Using responsive utility variants to build adaptive user interfaces.

Overview

Moreover, Every utility class in Tailwind can be applied conditionally at different breakpoints, which makes it super easy to build complex responsive interfaces in addition to ever leaving your HTML.

  • md: 768px
  • lg: 1024px
  • xl: 1280px
  • 2xl: 1536px

Furthermore, It supports all your pseudo-classes

Every utility class in Tailwind can be applied conditionally by adding a modifier to the beginning of the class name that describes the condition you want to target.

Tailwind dark mode

And finally, Now the tailwind awesome dark mode feature is a first-class feature for many operating systems, it’s becoming more and more common to design a dark version of your website.

The reason for that is trends or some health reasons to go along with the default design. A dark pseudo-class is well provided in tailwind:

  <div className="text-black dark:text-white">

Adding Custom Styles

Furthermore creating UI’s biggest challenge is when working with a framework and figuring out what you’re supposed to do when there’s something you need that the framework doesn’t handle for you.

Tailwind has many options for that condition as well and Tailwind is too extensible and customizable. So that no matter what you’re building you never feel like you’re fighting the framework.

Some ways are:

Customize through config file:

Furthermore, Want to change things like your spacing scale, or typography scale add your customizations to the theme section of your tailwind.config.js file:

module.exports = {
  theme: {
    extend: {
      spacing: {
        '128': '32rem',
        '144': '36rem',
      },
      textSize: {
        '4xl': '2rem',
      }
    }
  }
}
By arbitrary values:

While creating well-crafted designs using a set of design tokens, once in a while you need to break out of those tailwind constraints to get things to look as good as you need.

When you find yourself really needing something like font: 2rem to get a text in just the right size, use Tailwind’s square bracket notation to generate a class with any arbitrary value:

<h2 className="text-[2rem]">
 You can customize any thing like this
</h2>
Arbitrary properties

Like arbitrary values, if you ever need to use a CSS property that Tailwind doesn’t include a utility for out of the box then no worries.

You can also use square bracket notation to write completely arbitrary CSS:

<div className="hover:[mask-type:alpha]">
<p>You can design in your own way by this.</p>
</div>
Arbitrary variants

Arbitrary variants these are are like arbitrary values but for doing selector modification in a tailwinds way like you have a built-in pseudo-class for that variant

<ul role="list" className="lg:[&:nth-child(3)]:hover:underline">
    <li >item1</li>
    <li >item2</li>
    <li >item3</li>
</ul>
White spaces

You can handle white space in your custom classes by an _ and if you need an underscore in any case use \_. Ways of doing this are:

//If you need a space

className="before:content-['tailwind_nextjs']"

/* if you need a underscore
String.raw() so the backslash isn’t treated as a JavaScript escape character. */

className={String.raw`before:content-['tailwind\_nextjs']`}
And finally, custom CSS

If you want to add too many customs you can also add this way:

@tailwind base;
@tailwind components;

/* This will always be included in your compiled CSS */
.card {
  background-color: lightblue;
}

@tailwind utilities;
Plugins

You can use any number of plugins to create UI like cssnano, forms, typography, and other things. You can add them in this way:

//tailwind plugins in tailwind config
module.exports = {
  // ...
  plugins: [
    require('@tailwindcss/forms'),
    require('@tailwindcss/typography'),
  ],
}

//and other plugins in postcss config
module.exports = {
  plugins: {

    ...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
  }
}

Note: cssnano takes your nicely formatted CSS and runs it through many focused optimizations, to ensure that the final result is as small as possible for a production environment.

Now you are ready to use tailwind:

Now you are free to use Tailwind on your own after creating this much and you are free to Read it again.

For more info visit tailwind’s official documentation: https://tailwindcss.com/docs/installation.

For next.js you can visit: https://nextjs.org/

Check out Tailwind implementation with Mui as well in Next.js here.

Supported Framework Version - Next.js: 13 + Tailwind: 3.2

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home