Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Tailwind CSS

Tailwind CSS is a library of small ready-made classes: p-4 sets padding, text-xl the font size, rounded-lg rounded corners. Styles are written right in className, without a separate CSS file. Only the classes you actually use end up in the final build.

Where it is set up

If you answered "Yes" to the Tailwind question when creating the project, everything is ready. The first line of app/globals.css:

/* app/globals.css */
@import 'tailwindcss';

The project generator also added a postcss.config.mjs file with the @tailwindcss/postcss plugin. This is Tailwind CSS version 4: it needs no separate tailwind.config.js.

The first classes

Let us rewrite the post card with Tailwind:

// components/PostCard.tsx
import Link from 'next/link';
 
export default function PostCard({ slug, title }: { slug: string; title: string }) {
  return (
    <article className="mb-3 rounded-lg border border-gray-200 p-4">
      <h2 className="text-xl font-semibold">
        <Link href={`/posts/${slug}`} className="text-blue-600 hover:underline">
          {title}
        </Link>
      </h2>
    </article>
  );
}

On /posts the cards look the same as with the CSS module, and hovering a title underlines it.

Reading the classes

ClassCSS
p-4padding: 1rem
mb-3margin-bottom: 0.75rem
text-xlA larger font
font-semiboldfont-weight: 600
rounded-lgRounded corners
hover:underlineUnderline on hover
md:flexdisplay: flex on screens from 768px

The prefixes hover:, focus:, md:, lg: apply a class only in that state or at that screen width.

Your own colours

Theme colours and sizes are set in app/globals.css with a @theme block:

/* app/globals.css */
@import 'tailwindcss';
 
@theme {
  --color-brand: #7c3aed;
}

After that the classes text-brand, bg-brand, border-brand are available — for example className="bg-brand text-white" for the Publish button.

Adding it to an existing project

If you did not choose Tailwind when creating the project:

npm install tailwindcss @tailwindcss/postcss postcss

Then create postcss.config.mjs with the @tailwindcss/postcss plugin and add @import 'tailwindcss' at the top of app/globals.css.

Common mistake

Building a class name from parts: className={`text-${color}-600`}. Tailwind looks for classes in the source code as whole words and never learns about text-red-600, so the style does not appear. Write classes in full, for example choose between 'text-red-600' and 'text-green-600' with a condition.

Thanks for reading!

Donate to the site — we work hard for you.