🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Tailwind CSS in Next.js: Utilities to Dark Mode

Next.js StylingđŸŸĸ Free Lesson

Tailwind CSS in Next.js: Utilities to Dark Mode

Tailwind's premise is that reading a class list tells you what an element looks like, so design decisions live where you can see them instead of three files away. The premise only holds if the compiler can see your class names too. Every Tailwind bug in a Next.js project traces back to that one dependency: a class the scanner cannot find is a class that never exists at runtime, and the symptom — a layout with no padding — looks exactly like a CSS specificity problem while having nothing to do with the cascade.

This lesson covers how the scanner finds classes, where the theme belongs, how to add a colour that is actually usable, and how to make dark mode switch without painting the wrong colours for a frame.

Prerequisites

  • !Basic CSS and utility-class thinking
  • !How Next.js compiles global CSS in the app directory
  • !A Next.js project you can build locally

What You'll Learn

  • 1Explain why a dynamically constructed Tailwind class is missing in production
  • 2Configure content detection and extend the theme with design tokens
  • 3Add custom colours, spacing and fonts without fighting the defaults
  • 4Implement class-based dark mode with no flash on load

The scanner is the whole contract

Tailwind reads your source files, extracts anything that looks like a class name, and generates only the CSS those names need. In the current version you do not maintain a content array by hand — the framework integration scans your components automatically — but the rule behind it is unchanged: if a string never appears in a file the scanner reads, the utility is never generated.

// This works — the full class name is visible in source.
export function Badge({ children }) {
  return (
    <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-800">
      {children}
    </span>
  );
}

// This silently fails — the scanner sees "bg-" and a template, not the value.
export function BadgeBroken({ tone }) {
  return <span className={`bg-${tone}-100`}>{children}</span>;
}

The fix is always the same: put the complete class names somewhere static.

// components/StatusBadge.jsx
const TONE = {
  draft: 'bg-slate-100 text-slate-700 ring-slate-200',
  live: 'bg-emerald-100 text-emerald-800 ring-emerald-200',
  archived: 'bg-amber-100 text-amber-800 ring-amber-200',
};

export function StatusBadge({ status, children }) {
  const tone = TONE[status] || TONE.draft;
  return (
    <span className={`rounded-full px-3 py-1 text-xs font-semibold ring-1 ${tone}`}>
      {children}
    </span>
  );
}

The map costs four lines and removes an entire category of bug. It also documents the palette, which is the practical benefit teams notice after a month.

Where the theme belongs

Tailwind ships a default scale — spacing steps of a quarter rem, a slate-to-rose colour ramp, three font stacks — and the right way to extend it is with tokens that describe your product rather than your screens. A brand colour defined once is usable everywhere as bg-brand, text-brand, ring-brand, and border-brand with no further configuration.

javascript
// tailwind.config.ts
import type { Config } from 'tailwindcss';

const config: Config = {
  darkMode: 'class',
  theme: {
    extend: {
      colors: {
        brand: {
          50: '#eef6ff',
          500: '#2563eb',
          600: '#1d4ed8',
          700: '#1e40af',
        },
        surface: 'var(--surface)',
        ink: 'var(--ink)',
      },
      spacing: {
        '18': '4.5rem',
        '112': '28rem',
      },
      fontFamily: {
        sans: ['var(--font-sans)', 'system-ui', 'sans-serif'],
      },
      borderRadius: {
        card: '0.75rem',
      },
    },
  },
  plugins: [],
};

export default config;

Three choices in that file are worth defending. Mapping surface and ink to CSS variables means a theme switch changes one variable rather than every class name. Adding only the spacing steps you actually use keeps the generated stylesheet small instead of unlocking the entire scale. And a named card radius stops the magic number 0.75rem from being retyped in forty components.

Custom utilities that do not fit the scale — a specific gradient, a focus ring recipe — go through @utility in your CSS entry file rather than through @apply, which tends to hide behaviour inside a selector you have to open another file to understand.

Reset, entry point, and what ships

Tailwind v4 pulls the framework in through CSS rather than through a JavaScript config at the top of your entry file, and Next.js only needs one import in the root layout.

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

@theme {
  --font-sans: 'Inter', system-ui, sans-serif;
  --color-brand-500: #2563eb;
}

/* Custom properties that dark mode will rewrite */
:root {
  --surface: #ffffff;
  --ink: #0f172a;
  --line: #e2e8f0;
}

.dark {
  --surface: #0f172a;
  --ink: #f1f5f9;
  --line: #1e293b;
}
// app/layout.js
import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body className="bg-surface text-ink antialiased">{children}</body>
    </html>
  );
}

suppressHydrationWarning on the html element is not decoration. The theme script below runs before React hydrates and may set a class the server did not render; without the flag, React logs a mismatch warning for a difference you introduced deliberately.

Dark mode without the flash

Class-based dark mode requires three pieces to agree: the config must opt into class strategy, something must set the dark class on the root, and that something must run before the first paint. Putting it in a React effect guarantees a flash, because effects run after the browser has already drawn the light theme.

// app/theme-script.js — inlined in the document head
export const themeInit = `
(function () {
  try {
    var stored = localStorage.getItem('theme');
    var system = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    var theme = stored || system;
    if (theme === 'dark') document.documentElement.classList.add('dark');
  } catch (e) {
    /* storage blocked — fall back to the light defaults */
  }
})();
`;

Render that string into a script tag in the root layout's head, or inline it directly in the markup. Then wire a toggle that writes localStorage and flips the class, and subscribe to prefers-color-scheme changes so a user who switches their OS theme sees the app follow along while no explicit choice has been stored.

Two details make this behave like a product rather than a demo: resolve the system preference when the stored key is absent, and treat storage exceptions as a normal case, since privacy modes can throw on access.

Pair the toggle with an explicit three-state control if your audience includes people who switch devices often: light, dark, and follow the system. Writing system back to localStorage and resolving it at load time means a user who chose "follow my OS" is never frozen into whatever the theme happened to be on the day they clicked. Whatever you store, keep the key name boring and versioned — a schema change to an unversioned preference silently resets everyone's choice the moment you ship it.

What ends up in the stylesheet

Because utilities are generated on demand, the size of your CSS depends on how many distinct class names appear in source, not on how many components you ship. A hundred components that all use px-4 py-2 text-sm cost less than five components that each invent an arbitrary width. That relationship is the practical argument for a small, shared vocabulary: consistency and bundle size improve together.

The production build drops the reset, the defaults you never reference, and every media query whose class is absent. What remains is scanned for three things that commonly bloat it. Arbitrary values multiply rules — each unique w-[28rem]-style class creates its own declaration, so a design file full of one-pixel variations produces a stylesheet full of near-duplicates. Variant depth does the same: a class that is md:hover:focus-visible:disabled: deep exists for exactly one element and one breakpoint. And unused framework plugins contribute their full output even if you only ever call one of their utilities.

A quick audit after a build is enough: open the generated CSS, search for a utility you are sure nothing uses, and confirm it is gone. If it is still there, something in your source — often a stale test fixture, a string in a storybook story, or a class embedded in content data — is keeping it alive.

Layout utilities you will actually use

Most day-to-day Tailwind in a Next.js app is not colour at all — it is the small set of layout primitives that replace hand-written media queries. Knowing which ones reach for which breakpoint keeps markup readable.

GoalUtilitiesNotes
Two columns that stack on mobilegrid grid-cols-1 md:grid-cols-2 gap-6Mobile-first: base is the small screen
Sidebar beside contentflex flex-col md:flex-row plus md:w-64 shrink-0Add min-w-0 to the content child to stop overflow
Clamp text without ellipsistext-sm md:text-base leading-relaxedPrefer fewer breakpoints over many
Hide on small screenshidden md:blockKeeps markup for print and desktop only
Full-bleed section, centred innerw-full plus mx-auto max-w-6xl px-4The container idiom

Every prefix in that table is a min-width query, which is why Tailwind is described as mobile-first: you write the narrow layout as the default and add complexity as space allows. lg: and xl: exist for the same purpose, and arbitrary values such as w-[28rem] cover the one-off case without editing config.

Common Mistakes

Concatenating class names from variables

Fix: Use a static lookup map containing the complete class strings so the scanner can see every variant.

Toggling dark mode in a React effect

Fix: Run a tiny inline script in the head so the class is applied before first paint, and suppress hydration warnings on the html element.

Reaching for arbitrary values instead of a token

Fix: If a value appears more than twice, add it to the theme once and use the named utility everywhere after.

Styling a component's dark variant twice in two files

Fix: Keep dark pairs together — light and dark declarations for one element belong in one className list so the relationship stays visible.

Best Practices

  • Define brand colours as tokens and let the default scale handle the rest
  • Prefer a small, documented set of layout patterns over bespoke combinations
  • Keep utility strings in the component that owns the markup, not in a shared constants file
  • Verify the production build with a colour that only exists in one rare variant — if it renders, scanning works

Key Takeaways

  • Tailwind generates CSS only for class names it can find in source; constructed strings are never emitted.
  • Extend the theme with product tokens such as brand, surface and ink rather than scattered arbitrary values.
  • Class-based dark mode needs a pre-paint script, a stored or system preference, and suppressHydrationWarning.
  • Mapping semantic colours to CSS variables lets a theme switch happen without touching class names.
  • Utility breakpoints are min-width and mobile-first, so the base styles describe the narrow screen.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement