#nextjs #styling #tailwind #fonts

Day 5 β€” Styling & Fonts: Tailwind, CSS Modules, & Optimization

🧭 Day 5 β€” Styling & Fonts: Tailwind, CSS Modules, & Optimization

Zero to Hero β€” Hands-on Next.js Tutorial

Next.js is unopinionated about styling, but it has two β€œhappy paths”: Tailwind CSS and CSS Modules. It also has a superpower for performance: next/font.


🟦 1. Tailwind CSS (The Standard)

If you selected β€œYes” to Tailwind during setup, you are ready to go. Next.js pre-configures postcss.config.js and tailwind.config.ts.

Usage: Just add classes to your JSX.

<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Click Me
</button>

Tailwind Merge (cn utility): In robust Next.js apps, we often use clsx and tailwind-merge to combine classes dynamically.

npm install clsx tailwind-merge

🟩 2. CSS Modules (The Scoped Way)

If you dislike utility classes, use CSS Modules. They auto-generate unique class names to prevents conflicts (e.g., Button_btn__1a2b3).

  1. Create styles.module.css:
    .btn {
      background: blue;
      color: white;
    }
  2. Import and use it:
    import styles from './styles.module.css';
    
    <button className={styles.btn}>Click Me</button>

🟧 3. Optimizing Fonts (next/font)

Fonts are usually the #1 cause of Cumulative Layout Shift (CLS) (text flickering/moving). Next.js eliminates this by:

  1. Downloading the font at build time.
  2. Hosting it on your server (no requests to Google Fonts).
  3. Injecting fallback CSS to match the font size perfectly while loading.

Optimizing Google Fonts:

// src/app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google'

// Configure it
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter', // CSS Variable
})

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.variable}>
      <body className="font-sans">{children}</body>
    </html>
  )
}

Now use font-sans in Tailwind, and it uses the optimized Inter font!


πŸŸ₯ 4. Global Styles

For global resets or variables, simply edit src/app/globals.css. This file is imported in your Root Layout and applies everywhere.

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

/* Custom Global Styles */
body {
  background: #f0f0f0;
}

πŸ§ͺ Challenge: Day 5

  1. Pick a funky font from next/font/google (e.g., Lobster or Playfair Display).
  2. Import it in your Root Layout.
  3. Apply it only to <h1> tags using Tailwind (e.g., extend the theme in tailwind.config.ts or use a CSS variable).
  4. Create a β€œCard” component styled entirely with Tailwind utility classes.

See you tomorrow for Next.js Image Optimization! πŸ–ΌοΈ