UI and Styling: Making It Look Good
8 min read
UI and Styling: Making It Look Good π¨
Welcome back! Now that we have the basic structure of our Next.js app, it's time to make it look... well, not like a plain HTML page from 1999. In this guide, we'll explore the most common and industry-standard ways to style your Next.js applications.
1. Global CSS and the Root Layout Integration
π€ Definition and Problem
Global CSS refers to stylesheets that apply to your entire application. Think of it as the base layer of paint for your whole house. It's where you define styles for common HTML elements (body, h1, a), CSS resets, or variables that every component might need.
The problem? In traditional web development, managing global CSS can become a nightmare. If you're not careful, you can end up in a "specificity war," where different stylesheets accidentally override each other. It's like two people trying to paint the same wall different colors at the same time β chaotic and unpredictable. You might change a style for one button and accidentally restyle every button on the site!
β Solution: The Root Layout
Next.js (with the App Router) brings order to this chaos by providing a simple rule: import global styles in your root layout file (app/layout.tsx). This file acts as the main shell for your entire application, making it the perfect and only place to load styles that should be, well, global.
By importing your global CSS file here, you ensure it's loaded once and applies everywhere, without the risk of it being loaded in an unpredictable order somewhere else.
π» Hands-On Example
Create your global stylesheet. By default, a new Next.js project includes
app/globals.css. Let's add some simple styles to it.css/* app/globals.css */ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-color: #f0f2f5; } a { color: #0070f3; text-decoration: none; } a:hover { text-decoration: underline; }Import it into the root layout. Open
app/layout.tsx(or.js) and make sure the import is at the top.tsx// app/layout.tsx import './globals.css'; // This line imports our global styles import type { Metadata } from 'next'; export const metadata: Metadata = { title: 'My Styled App', description: 'Learning about styling in Next.js', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); }
And that's it! These styles will now be applied to every page in your application.
π‘ Fun Fact: The chaos of global CSS is what led to the creation of many modern styling solutions. Developers spent so much time debugging CSS specificity issues that they decided to invent new ways to avoid the problem altogether.
2. CSS Modules: Scoped and Traditional Styling
π€ Definition and Problem
What happens when you have two different components that both need a .title class, but with different styles? With global CSS, the last one loaded wins, causing a conflict. You could create unique class names like .UserProfile_title and .ProductCard_title, but that's tedious and prone to error.
This is a problem of scope. We need a way to make a stylesheet "belong" to a single component.
β Solution: CSS Modules
CSS Modules solve this by locally scoping your styles. They are CSS files where every class name is automatically made unique to the component that imports it. This lets you use simple class names like .title or .button in different files without ever worrying about them clashing.
Next.js has built-in support for CSS Modules. All you have to do is name your file with the .module.css extension.
βοΈ Under the Hood: When you build your project, Next.js processes these module files. It takes your class name (e.g., .title) and generates a unique one (e.g., ComponentName_title__aBc12). This ensures the styles are applied only where you import them.
π» Hands-On Example
Create a component and its CSS module. Let's make a simple
InfoCardcomponent.app/components/InfoCard.tsxapp/components/InfoCard.module.css
Write the styles in the module file.
css/* app/components/InfoCard.module.css */ .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); max-width: 300px; } .title { font-size: 1.5rem; color: #333; margin-top: 0; }Import and use the styles in your component.
tsx// app/components/InfoCard.tsx import styles from './InfoCard.module.css'; export default function InfoCard() { return ( <div className={styles.card}> <h2 className={styles.title}>Hello from InfoCard!</h2> <p>This component has its own scoped styles.</p> </div> ); }
Now, the .card and .title classes from InfoCard.module.css will only apply to the InfoCard component, no matter what other stylesheets you have.
3. Tailwind CSS in Next.js: The Industry Standard Setup
π€ Definition and Problem
Writing custom CSS for every little thing is time-consuming. You constantly switch between your JSX and CSS files, and you have to invent class names for everything. What if you could style things directly in your HTML/JSX without ever leaving the file?
β Solution: Tailwind CSS
Tailwind CSS is a utility-first CSS framework. Instead of giving you pre-styled components (like Bootstrap's .btn-primary), it gives you low-level utility classes like p-4 (padding: 1rem), text-white, and bg-blue-500. You combine these "building blocks" to create any design you want, directly in your markup.
It's the most popular styling solution in the Next.js ecosystem because it's fast, consistent, and helps keep your CSS bundle size small since it only includes the styles you actually use.
π Getting Started: Installation
The easiest way to start a new Next.js project with Tailwind CSS is during the setup process.
npx create-next-app@latest my-tailwind-appWhen prompted, answer "Yes" to "Would you like to use Tailwind CSS?". This will automatically configure everything for you.
For an existing project, follow these steps:
Install the necessary packages:
bashnpm install -D tailwindcss postcss autoprefixerInitialize Tailwind: This creates the
tailwind.config.jsandpostcss.config.jsfiles.bashnpx tailwindcss init -pConfigure your template paths: Open
tailwind.config.jsand tell Tailwind which files to scan for utility classes.js/** @type {import('tailwindcss').Config} */ module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', './app/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: {}, }, plugins: [], };Add Tailwind directives to your global CSS: Open
app/globals.cssand replace its content with the following lines.css@tailwind base; @tailwind components; @tailwind utilities;
Your project is now set up and ready to use Tailwind!
π» Hands-On Example
Let's build a simple button with Tailwind.
// In any component, e.g., app/page.tsx
export default function HomePage() {
return (
<main className="flex items-center justify-center min-h-screen">
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-md transition-colors duration-300">
Click Me
</button>
</main>
);
}Look at that! No CSS files needed. We've created a styled, interactive button just by combining utility classes.
4. Conditional Styling Mastery with clsx and tailwind-merge
π€ Definition and Problem
Styling is often dynamic. A button might be blue by default, gray when disabled, or green when successful. Writing the logic for this in the className prop can get very messy.
// This gets complicated quickly!
<button
className={`base-styles ${isActive ? 'active-styles' : 'inactive-styles'} ${
isLoading ? 'loading-styles' : ''
}`}
>Furthermore, with Tailwind, you can accidentally apply conflicting classes. For example, if a component has a default of p-2 but you pass in a prop to make it p-4, you might end up with <div class="p-2 p-4">. The browser will just apply whichever style came last in the CSS file, which is unpredictable.
β
Solution: The clsx and tailwind-merge Power Duo
To solve this, the industry standard is to use two small, powerful libraries together:
clsx: A tiny utility for constructingclassNamestrings conditionally from an object.tailwind-merge: Intelligently merges Tailwind CSS classes, resolving conflicts and removing redundancies. For example,twMerge('p-2 p-4')will correctly output justp-4.
Combining them gives you a clean, predictable way to handle complex, conditional styling.
π Getting Started: Installation
npm install clsx tailwind-mergeπ» Hands-On Example
It's a very common practice to create a helper utility function, often named cn (for "class names"), to combine these two libraries.
Create a utility function.
ts// lib/utils.ts import { type ClassValue, clsx } from 'clsx'; import { twMerge } from 'tailwind-merge'; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }Use the
cnfunction in a component. Let's create aButtoncomponent that can handle different visual variants and a disabled state.tsx// app/components/Button.tsx import { cn } from '@/lib/utils'; import React from 'react'; // Define props for the component interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { variant?: 'primary' | 'secondary' | 'destructive'; } const Button = ({ className, variant, ...props }: ButtonProps) => { const variants = { primary: 'bg-blue-600 text-white hover:bg-blue-700', secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300', destructive: 'bg-red-500 text-white hover:bg-red-600', }; return ( <button className={cn( 'px-4 py-2 rounded-md font-semibold transition-all duration-200', 'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500', 'disabled:opacity-50 disabled:cursor-not-allowed', // Style for disabled state variants[variant || 'primary'], // Apply variant styles className // Allow overriding with external classes )} {...props} /> ); }; export default Button;Now use your new super-powered button!
tsx// app/page.tsx import Button from './components/Button'; export default function HomePage() { return ( <div className="flex flex-col items-center justify-center min-h-screen gap-4"> <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button> <Button variant="destructive" disabled> Destructive (Disabled) </Button> <Button variant="primary" className="p-8 text-2xl"> Primary with Overrides </Button> </div> ); }
Notice how tailwind-merge in our cn function would correctly handle the last button. Even though the default Button style has px-4 py-2, the final output class will be p-8 text-2xl because it intelligently overrides the padding classes.
This pattern is extremely powerful and is used in almost every professional Next.js and React project that uses Tailwind CSS.
π References for Extra Reading
- Next.js Documentation:
- Libraries:
Challenge
Challenge: Create a Dynamic Status Badge Component
You are tasked with building a flexible StatusBadge React component using Tailwind CSS. The component's appearance must change based on the props it receives. To handle the complex conditional class names and potential style conflicts, you will use the provided cn utility function, which internally combines clsx and tailwind-merge.
Requirements:
Your goal is to implement the logic inside the className prop of the div element using the cn function.
The component must apply styles based on the following props:
- Base Styles: The badge should always have these base classes:
inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium. variantProp: Conditionally apply color classes based on thevariantprop. The default variant is'info'.'info':bg-blue-100 text-blue-800'success':bg-green-100 text-green-800'warning':bg-yellow-100 text-yellow-800'error':bg-red-100 text-red-800
isPulsingProp: IfisPulsingistrue, add theanimate-pulseclass.iconPositionProp: If an icon is present, adjust padding. This prop is optional.'left':pl-1.5'right':pr-1.5
classNameProp: The component must also accept an optionalclassNameprop to allow for external style overrides. This should be the last argument passed tocnto ensuretailwind-mergecorrectly prioritizes override classes.
Expected result
Expected Code Solution
The className attribute should be populated with a call to the cn function that includes the base styles and conditionally applies styles for variants, pulsing animation, icon position, and external overrides.
{
/* ... component code ... */
return (
<div
className={cn(
// 1. Base styles that are always applied
'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
// 2. Conditional styles for the 'variant' prop
{
'bg-blue-100 text-blue-800': variant === 'info',
'bg-green-100 text-green-800': variant === 'success',
'bg-yellow-100 text-yellow-800': variant === 'warning',
'bg-red-100 text-red-800': variant === 'error',
},
// 3. Conditional style for the 'isPulsing' prop
{ 'animate-pulse': isPulsing },
// 4. Conditional styles for the 'iconPosition' prop
{
'pl-1.5': iconPosition === 'left',
'pr-1.5': iconPosition === 'right',
},
// 5. Pass through the external className prop for overrides
className
)}
>
{children}
</div>
);
}Explanation:
This solution correctly uses clsx's object syntax to toggle classes based on prop values. By passing the external className prop last, tailwind-merge will intelligently resolve any conflicts. For example, if a user passes className="bg-purple-100 p-3", tailwind-merge will ensure bg-purple-100 overrides the variant's background color and p-3 overrides the base px-2.5 py-0.5 styles.