Module 8 ended by pointing out what AgendaViva still lacks: a polished look. So far we've written only the classes we couldn't do without, repeating text-teal-800 and border-slate-200 in every component. It works, but two problems are already showing: changing the brand color means searching through thirty files, and in dark mode some text is nearly unreadable, because nobody remembered to write its variant.

Next.js doesn't impose a way of styling. It accepts plain CSS, CSS Modules, Tailwind, Sass and several CSS-in-JS libraries, and they all end up the same way: as .css files the browser downloads. What changes is who decides the names, what reaches each page and which rule wins when two contradict each other. In this lesson you'll understand those three points, give AgendaViva a theme with meaning and choose a tool for each case.

  1. How CSS reaches the page

A CSS file enters the project because some module imports it:

import './globals.css'                   // Global: affects everything
import styles from './modal.module.css'  // Local: returns an object of names
import 'example-library/styles.css'      // From a package

At build time, Next.js gathers those files, minifies them and splits them into several chunks, so that each route downloads something close to what it uses. The split is based on imports, not on what's visible: if a component on the page imports a stylesheet, the stylesheet arrives even if the component isn't rendered.

  • Styles block painting, on purpose: without them you'd briefly see the bare page. That's why their size matters.
  • React waits for the stylesheets of a Suspense boundary before showing its content.
  • Stylesheets aren't removed when navigating. The documentation warns about it: global CSS imported by one page stays active on the next. An h1 { color: red } rule imported in /venues will tint the headings of /events depending on where the visitor has been.
  • In development, the order may differ from production. A style conflict is checked with next build.

The third bullet gives the first rule: global CSS only for what's truly global, and in the root layout.

  1. Tailwind, from the inside

Tailwind generates one class for each declaration you use. There's no huge stylesheet with every possibility: at build time it scans the project files, looks for text that resembles classes and writes only those.

In our project it's wired in by the rule the generator left in next.config.ts (01-02):

turbopack: {
  rules: {
    '*.css': { loaders: ['@tailwindcss/turbopack'], as: '*.css' },
  },
},

Every CSS file goes through that loader, which understands @import "tailwindcss", @theme and the other directives. In many projects, and in much of the documentation, you'll see another setup: a postcss.config.mjs with @tailwindcss/postcss. The result is the same; it's the one you need if you build with Webpack. Don't use both.

Version 4 doesn't need tailwind.config.js: the configuration lives in the CSS. It requires browsers from roughly 2023 onwards (Chrome 111, Safari 16.4, Firefox 128); for older ones there's version 3.

2.1. What Tailwind can't see

The scanner treats your code as text: it doesn't run it. That's why this component has no color:

// Wrong: "text-red-700" isn't written anywhere
<span className={`text-${status === 'canceled' ? 'red' : 'teal'}-700`}>

// Right: the full names appear in the code
<span className={status === 'canceled' ? 'text-red-700' : 'text-teal-700'}>

The mistake is treacherous, because sometimes it works: all it takes is another file using the same class. When there are several variants, you write a lookup table with full names (section 4). And if the value is truly arbitrary, like a percentage, you use style with a variable: style={{ width: ${occupancy}% }}.

node_modules, whatever Git ignores and the CSS files themselves aren't scanned. For a Tailwind-based component library you have to add its folder with @source.

  1. A theme with meaning

text-slate-600 says what color it is. What a component wants to say is "secondary text", and let someone else decide the value. Those names are called tokens, and they solve the brand change and dark mode at the same time: components name the purpose, and the theme assigns the color.

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

@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));

:root {
  color-scheme: light;
  --background: #f8fafc;
  --surface: #ffffff;
  --foreground: #0f172a;
  --muted: #475569;
  --border: #cbd5e1;
  --accent: #115e59;
  --on-accent: #ffffff;
  --danger: #b91c1c;
}

[data-theme='dark'] {
  color-scheme: dark;
  --background: #020617;
  --surface: #0f172a;
  --foreground: #f1f5f9;
  --muted: #cbd5e1;
  --border: #334155;
  --accent: #5eead4;
  --on-accent: #042f2e;
  --danger: #fca5a5;
}

@theme inline {
  --color-background: var(--background);
  --color-surface: var(--surface);
  --color-foreground: var(--foreground);
  --color-muted: var(--muted);
  --color-border: var(--border);
  --color-accent: var(--accent);
  --color-on-accent: var(--on-accent);
  --color-danger: var(--danger);
}

@layer base {
  :focus-visible {
    outline: 2px solid var(--accent);
    outline-offset: 2px;
  }
}

There are two levels, with different roles:

  • :root and [data-theme='dark'] hold the values, in ordinary CSS variables. The attribute is the one set by the script from 03-04.
  • @theme declares variables that also create classes. The --color- prefix produces bg-surface, text-muted, border-border… Other prefixes generate other families: --font-*, --text-*, --breakpoint-*, --radius-*, --shadow-*.
  • inline makes the class use var(--surface) directly rather than an intermediate variable. It's recommended when a theme value points to another variable: that way it's resolved on the element where it's used, which is what allows it to change with the attribute.

@theme must be at the top level of the file; it can't go inside a selector. Hence the separation: values change in :root, and the theme just names them.

The values weren't picked by eye. At level AA, the WCAG standard requires a contrast of at least 4.5:1 for text and 3:1 for essential elements, such as the border of a field:

Pair Light Dark
foreground on background 17.1 18.4
muted on surface 7.6 12.0
accent on surface 7.6 12.1
on-accent on accent 7.6 9.8
danger on surface 6.5 9.4
border on surface 1.5 1.7

The last row doesn't reach 3, which is why border works for separating cards, which are also told apart by spacing, but not as the only outline of a form field: there you use border-muted. And the text-teal-800 we had scores 2.4 on the dark surface: the guide's name was barely readable.

3.1. Replacing

Before Now
bg-slate-50 … dark:bg-slate-950 bg-background
bg-white … dark:bg-slate-900 bg-surface
text-slate-600 dark:text-slate-300 text-muted
border-slate-200 dark:border-slate-700 border-border
text-teal-800 text-accent
text-red-700 text-danger
// app/layout.tsx (the <body>)
<body className="flex min-h-screen flex-col bg-background text-foreground">
  <ThemeProvider>{children}</ThemeProvider>
</body>

// components/event-card.tsx (the <article>)
<article className="min-h-44 rounded-lg border border-border bg-surface p-4">

The dark: variants almost disappear. Keep @custom-variant for what isn't a theme color, such as a shadow that only makes sense in light mode. The project ends up like this: components use tokens, and palette colors only appear in globals.css.

  1. Variants and conditional classes

With many conditions, template strings become unreadable and leave spaces or the word false inside the class. A small function tidies it up. There are equivalent libraries, such as clsx; a few lines are enough for us:

// lib/classes.ts
export function joinClasses(...classes: (string | false | null | undefined)[]): string {
  return classes.filter(Boolean).join(' ')
}
// lib/styles.ts — full names, so Tailwind can find them
const BASE = 'inline-flex min-h-11 items-center rounded-md px-4 font-medium disabled:opacity-60'

export const BUTTON = {
  primary: `${BASE} bg-accent text-on-accent hover:opacity-90`,
  secondary: `${BASE} border border-muted bg-surface hover:bg-background`,
  danger: `${BASE} border border-danger text-danger hover:bg-background`,
} as const

export const TEXT_FIELD =
  'w-full rounded-md border border-muted bg-surface px-3 py-2 aria-invalid:border-danger'

BASE can go into a template string without trouble: what you can't build is a class name, and here they're all whole. aria-invalid: applies the style when the field has that attribute, which we were already setting in 06-02 for screen readers: appearance and semantics come from the same place and can't disagree.

Apply them where appropriate: <SubmitButton className={BUTTON.primary} …>, links that look like buttons and the <input> elements in forms. A component with variants follows the same pattern:

// components/status-badge.tsx
import { joinClasses } from '@/lib/classes'
import { STATUS_LABELS } from '@/lib/format'
import type { EventStatus } from '@/lib/types'

const APPEARANCE: Record<EventStatus, string> = {
  draft: 'border-dashed border-muted text-muted',
  review: 'border-muted',
  published: 'border-accent text-accent',
  canceled: 'border-danger text-danger line-through',
}

export function StatusBadge({ status }: { status: EventStatus }) {
  return (
    <span className={joinClasses('rounded-full border px-2 py-0.5 text-sm', APPEARANCE[status])}>
      {STATUS_LABELS[status]}
    </span>
  )
}

Use it in the DashboardEventsPage table. The Record forces you to decide on an appearance if a status is ever added: without one, TypeScript won't compile.

Why a component and not a custom class with @apply? Because in React the unit of reuse is the component, which carries the HTML and the text along with it, not just the color. @apply makes sense for styling HTML you don't write yourself.

4.1. Two classes that contradict each other

If a component sets p-4 and whoever uses it passes p-8, which one wins? Not the last one in the attribute. All Tailwind classes have the same weight, and their order in the generated stylesheet decides. The simple solution is not to accept contradicting classes: offer variants (size="large") or let the container set the margins. The tailwind-merge library removes contradictions at runtime, at the cost of JavaScript if it's used on the client.

  1. CSS Modules

A *.module.css file is imported as an object, and its classes get a unique name at build time. Two components can both have .title without knowing about each other. It's full CSS, with no new vocabulary: the natural choice for what Tailwind expresses poorly, such as an animation with several states. Our modal (02-05) appears abruptly; let's give it an entrance:

/* app/(public)/events/_components/modal.module.css */
.dialog {
  width: 100%;
  max-width: 32rem;
  margin: auto;
  padding: 1.5rem;
  border-radius: 0.5rem;
  color: var(--foreground);
  background: var(--surface);
}

.dialog::backdrop {
  background: rgb(0 0 0 / 0.5);
}

@media (prefers-reduced-motion: no-preference) {
  .dialog[open] {
    transition: opacity 150ms ease-out, translate 150ms ease-out;
  }

  @starting-style {
    .dialog[open] {
      opacity: 0;
      translate: 0 1rem;
    }
  }
}
// app/(public)/events/_components/modal.tsx
import styles from './modal.module.css'

<dialog ref={dialogRef} className={styles.dialog} /* … the rest, unchanged … */ >
  • @starting-style sets the values from which the transition of an element that has just appeared starts. Where it isn't supported, the dialog appears without animation.
  • The animation is inside prefers-reduced-motion: no-preference: it only animates for people who haven't asked otherwise.
  • It uses var(--surface), our variables, and not Tailwind classes. That way the file doesn't need Tailwind at all.
  • @keyframes is local too in a module. A selector that must be global is wrapped in :global(.class-name).

And @apply inside a module? Each module is processed separately and doesn't know the theme; you'd have to start with @reference "../../../globals.css". Tailwind's documentation advises against mixing them like that: each module costs it an extra pass. With CSS variables it isn't needed.

5.1. Who wins between Tailwind and a module

Tailwind writes its utilities inside a layer (@layer utilities), and in CSS whatever is not in any layer beats whatever is, regardless of specificity. The consequence: with className={joinClasses(styles.dialog, 'p-2')}, the module's padding prevails and p-2 does nothing. It isn't a bug, and moving imports around won't fix it. Project rule: one property, one tool; on the same element it's never set twice.

Between two modules, on the other hand, order does matter, and it depends on the import order: the one imported later goes after. That's why a component should import its children first and then its own stylesheet, and why you should disable the rules that sort imports alphabetically if there's CSS among them.

  1. Sass

Next.js understands .scss and .sass, also as modules, just by installing sass (npm install --save-dev sass). Options go in sassOptions:

// Example only: components/billboard.module.scss
@use 'sass:map';

$widths: (narrow: 1, medium: 2, wide: 4);

.billboard {
  display: grid;
  gap: 1rem;

  @each $name, $columns in $widths {
    &.#{$name} {
      grid-template-columns: repeat($columns, 1fr);
    }
  }
}

For years Sass provided variables, nesting and calculations that CSS lacked. Today browsers have all three, and their variables are better for a theme: they exist at runtime and change with an attribute, whereas $color is replaced at build time and disappears. What's still worthwhile are loops, mixins and, above all, code that's already written: in a migration it's used as is.

Two limits. The functions option, for defining functions in JavaScript, doesn't work with Turbopack. And Tailwind 4 isn't designed to be combined with Sass: don't write @import "tailwindcss" in a .scss file. They can coexist in the same project, each in its own files.

  1. CSS-in-JS

Libraries that compute styles at runtime, such as styled-components, need hooks and context. Therefore:

  • They only work in Client Components. Every styled component drags its JavaScript along, which is the opposite of what we've been aiming for since module 3.
  • They need a registry: a client component that wraps the application, collects the rules during server rendering and inserts them with useServerInsertedHTML before the content that uses them.
  • Each library must support React's concurrent and streamed rendering. The documentation keeps a list; check it before choosing.

Another group resolves styles at build time and produces plain CSS: vanilla-extract, Panda CSS or StyleX. They give you types and composition from TypeScript at no cost in the browser, in exchange for adding one more step to the build; with Turbopack, confirm they're supported.

For a project that already uses styled-components, the reasonable path is to keep it in its islands and write new code with something else.

  1. The CSP and styles

Our policy (08-05) allows style-src 'self' 'unsafe-inline'. Stylesheets are served from here, so 'self' covers them. 'unsafe-inline' is needed for the rest: the style attribute that appears in the HTML, such as the width of a bar or what next/image writes, and the <style> tags inserted by the libraries in the previous section.

What's used Does it need 'unsafe-inline'?
Tailwind, CSS Modules, Sass No
style={{ … }} in a Server Component Yes: it's an HTML attribute
style changed by React in the browser No: it's assigned from JavaScript
Runtime CSS-in-JS Yes, or a nonce

An injected style is less serious than a script, but not harmless: it can cover the page or extract information with selectors and images. Another reason to keep img-src strict.

  1. Visual accessibility

What you decide in the CSS determines whether some people can use the page at all:

  • Focus is visible. The :focus-visible rule in globals.css guarantees it. outline: none with no alternative leaves keyboard users not knowing where they are.
  • Color isn't the only message. StatusBadge writes the text, and each status also differs in its stroke.
  • Relative units. Tailwind uses rem, so text grows if it's enlarged in the browser. With fixed pixel heights it would get cut off: use min-h-*.
  • Touch targets. WCAG 2.2 requires, at level AA and with some exceptions, 24 by 24 pixels; min-h-11 gives 44, which is more comfortable on a phone.
  • Reduced motion. With Tailwind, motion-safe:animate-pulse on skeletons.
  • Hide things properly. hidden hides from everyone; sr-only, only from sight.

One detail is missing, and you notice it when you move through the page with the Tab key: you have to go through the whole header on every page. It's solved with a link to skip it, invisible until it receives focus:

// components/skip-to-content.tsx
export function SkipToContent() {
  return (
    <a
      href="#content"
      className="sr-only focus:not-sr-only focus:absolute focus:z-10 focus:bg-surface focus:p-3"
    >
      Skip to content
    </a>
  )
}
// app/(public)/layout.tsx
export default function PublicLayout({ children }: LayoutProps<'/'>) {
  return (
    <>
      <SkipToContent />
      <Suspense fallback={null}>
        <SiteNotice />
      </Suspense>
      <Header />
      <main id="content" tabIndex={-1} className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
        {children}
      </main>
      <Footer />
    </>
  )
}

tabIndex={-1} lets the <main> element receive focus when the link is followed, without adding it to the tab order. Do the same in ManagementLayout and AccountLayout.

  1. Choosing

Need Tool
The product's colors, typography and spacing CSS variables and @theme, in globals.css
Almost every component Tailwind
Animations, complex selectors, pseudo-elements A CSS Module next to the component
HTML you don't write yourself, such as imported text A CSS Module or @layer base, scoped to a container
A value that depends on the data style with a CSS variable
Legacy code Sass, or whatever library is already there, without extending it
A third party's visual dependency Its CSS, imported where it's used

The hardest part isn't choosing badly, but choosing several at once for the same thing.

Common Mistakes and Tips

  • Building class names with template strings or concatenation.
  • Global CSS imported in a page. It isn't removed when navigating.
  • Writing @theme inside a selector for dark mode. Change the variables in :root and in the attribute.
  • Expecting the last class in the attribute to win.
  • Trying to make Tailwind override a CSS Module on the same property.
  • Having both postcss.config and the Turbopack rule.
  • Marking a page with 'use client' to use CSS-in-JS.
  • Removing the focus outline because it "looks ugly".
  • Setting pixel heights around text.
  • Checking CSS order only in development.

Exercises

Exercise 1: predict the result

Say what happens in each case and how you'd fix it: (a) className={border-${color}} with color="accent"; (b) <div className="text-lg text-sm">; (c) .box { padding: 2rem } in a module, and className={joinClasses(styles.box, 'p-0')}; (d) app/(public)/venues/page.tsx imports venues.css, which contains table { width: 100% }; (e) a Server Component imports styled from styled-components.

Solution

  • (a) The class may not be generated. Use a lookup table with 'border-accent' written in full.
  • (b) Whichever comes later in the generated stylesheet wins, not in the attribute. Keep only one.
  • (c) The module wins: it isn't in any layer and p-0 is. Create another class in the module, .noPadding, or remove the padding from there and always set it with Tailwind.
  • (d) After visiting /venues, tables on other pages change too, including those in the dashboard if you get there without reloading. Turn it into a module with a class.
  • (e) An error, because the library needs hooks and context. The component would have to be a client one, with the registry installed. With Tailwind or a module it stays on the server.

Exercise 2: high contrast

People who turn on "increase contrast" in their system send the prefers-contrast: more preference. Make AgendaViva respect it in both themes without touching any component.

Solution

/* app/globals.css, after the two themes */
@media (prefers-contrast: more) {
  :root {
    --muted: #1e293b;
    --border: #475569;
  }

  [data-theme='dark'] {
    --muted: #f1f5f9;
    --border: #cbd5e1;
  }
}

All components name tokens, so changing their values is enough. It's proof that the theme is well designed. Order matters: the rules have the same specificity as the earlier ones and win by coming after. Separately, there's forced colors mode, forced-colors: active, in which the browser replaces colors with the system's; there you should check that nothing depends solely on a background, because it disappears.

Exercise 3: an occupancy bar

In the dashboard overview, show occupancy with a bar whose length is the percentage of spots booked. You can't generate dynamic classes, it must be understandable to a screen reader and it must remain a Server Component.

Solution

// Practice only
export function OccupancyBar({ booked, capacity }: { booked: number; capacity: number }) {
  const percentage = capacity === 0 ? 0 : Math.round((booked / capacity) * 100)

  return (
    <div>
      <p className="text-sm">
        {booked} of {capacity} spots booked ({percentage}%)
      </p>
      <div aria-hidden className="mt-1 h-2 rounded-full bg-border">
        <div className="h-2 rounded-full bg-accent" style={{ width: `${percentage}%` }} />
      </div>
    </div>
  )
}

The arbitrary value goes in style, which the CSP allows. The text contains all the information and the bar is hidden from screen readers with aria-hidden: repeating it would add nothing. Another option is the <meter> element, accessible on its own, though harder to style consistently across browsers.

Conclusion

CSS arrives through imports, is split by route and isn't removed when navigating; that's why what's global is limited to the theme and the base. CSS variables hold the values, @theme turns them into classes with meaning, and dark mode is a change of values, not a second set of classes. Tailwind covers most of it, CSS Modules what's better expressed in CSS, and Sass and CSS-in-JS mostly legacy code. AgendaViva now uses names like bg-surface, has measured contrast ratios and can be navigated with the keyboard.

Two elements are still out of control, and they're the heaviest: posters, which are served at the size they were uploaded, and typography, which is whatever each device happens to have. Both also cause the jumps you see while loading. They're covered together in Optimized Images and Fonts.

© Copyright 2026. All rights reserved