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).
- Create
styles.module.css:.btn { background: blue; color: white; } - 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:
- Downloading the font at build time.
- Hosting it on your server (no requests to Google Fonts).
- 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
- Pick a funky font from
next/font/google(e.g.,LobsterorPlayfair Display). - Import it in your Root Layout.
- Apply it only to
<h1>tags using Tailwind (e.g., extend the theme intailwind.config.tsor use a CSS variable). - Create a βCardβ component styled entirely with Tailwind utility classes.
See you tomorrow for Next.js Image Optimization! πΌοΈ