Chapter 6: Styling and CSS in Next.js
What is Styling in Next.js?
Next.js provides multiple approaches for styling your applications, from traditional CSS to modern CSS-in-JS solutions. The framework supports various styling methods while maintaining excellent performance and developer experience.
Available Styling Options:
- Global CSS: Traditional CSS files for global styles
- CSS Modules: Scoped CSS with automatic class name generation
- Styled JSX: CSS-in-JS solution built into Next.js
- Sass/SCSS: Enhanced CSS with variables and mixins
- CSS-in-JS Libraries: Styled-components, Emotion, and others
- Utility-First CSS: Tailwind CSS and similar frameworks
Why Choose Different Styling Approaches?
Global CSS:
- Simple and familiar
- Good for reset styles and global variables
- Easy to integrate with existing CSS
CSS Modules:
- Scoped styles prevent conflicts
- Automatic class name generation
- Great for component-specific styles
Styled JSX:
- Built into Next.js
- No additional dependencies
- Dynamic styling with JavaScript
Sass/SCSS:
- Enhanced CSS features
- Variables, mixins, and functions
- Better organization for large projects
CSS-in-JS:
- Dynamic styling based on props
- Type safety with TypeScript
- Component-scoped styles
How to Implement Different Styling Methods
1. Global CSS
Setting up Global Styles:
/* styles/globals.css */
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
line-height: 1.6;
color: #333;
}
* {
box-sizing: border-box;
}
a {
color: #0070f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
img {
max-width: 100%;
height: auto;
}
/* CSS Variables */
:root {
--primary-color: #0070f3;
--secondary-color: #f0f0f0;
--text-color: #333;
--background-color: #fff;
--border-radius: 4px;
--spacing-unit: 8px;
}
/* Dark mode support */
@media (prefers-color-scheme: dark) {
:root {
--text-color: #fff;
--background-color: #000;
--secondary-color: #1a1a1a;
}
}
Importing Global Styles:
// pages/_app.js
import '../styles/globals.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
2. CSS Modules
Creating CSS Modules:
/* components/Button.module.css */
.button {
padding: 12px 24px;
border: none;
border-radius: var(--border-radius);
cursor: pointer;
font-size: 16px;
font-weight: 500;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
justify-content: center;
text-decoration: none;
}
.primary {
background-color: var(--primary-color);
color: white;
}
.primary:hover {
background-color: #0051cc;
transform: translateY(-1px);
}
.secondary {
background-color: var(--secondary-color);
color: var(--text-color);
}
.secondary:hover {
background-color: #e0e0e0;
}
.large {
padding: 16px 32px;
font-size: 18px;
}
.small {
padding: 8px 16px;
font-size: 14px;
}
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
.disabled:hover {
transform: none;
}
Using CSS Modules:
// components/Button.js
import styles from './Button.module.css'
import { clsx } from 'clsx'
export default function Button({
children,
variant = 'primary',
size = 'medium',
disabled = false,
className,
...props
}) {
const buttonClasses = clsx(
styles.button,
styles[variant],
styles[size],
{
[styles.disabled]: disabled,
},
className
)
return (
<button
className={buttonClasses}
disabled={disabled}
{...props}
>
{children}
</button>
)
}
3. Styled JSX
Basic Styled JSX:
// components/Card.js
export default function Card({ title, children, variant = 'default' }) {
return (
<div className="card">
<h3 className="title">{title}</h3>
<div className="content">{children}</div>
<style jsx>{`
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
padding: 24px;
margin: 16px 0;
transition: box-shadow 0.2s ease;
}
.card:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
.title {
margin: 0 0 16px 0;
color: #333;
font-size: 1.5rem;
font-weight: 600;
}
.content {
color: #666;
line-height: 1.6;
}
`}</style>
</div>
)
}
Dynamic Styled JSX:
// components/ProgressBar.js
export default function ProgressBar({ progress, color = '#0070f3' }) {
return (
<div className="progress-container">
<div className="progress-bar">
<div className="progress-fill" />
</div>
<span className="progress-text">{progress}%</span>
<style jsx>{`
.progress-container {
display: flex;
align-items: center;
gap: 12px;
}
.progress-bar {
flex: 1;
height: 8px;
background-color: #f0f0f0;
border-radius: 4px;
overflow: hidden;
}
.progress-fill {
height: 100%;
width: ${progress}%;
background-color: ${color};
transition: width 0.3s ease;
}
.progress-text {
font-size: 14px;
font-weight: 500;
color: #666;
min-width: 40px;
}
`}</style>
</div>
)
}
Global Styled JSX:
// components/GlobalStyles.js
export default function GlobalStyles() {
return (
<style jsx global>{`
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #333;
}
h1, h2, h3, h4, h5, h6 {
margin: 0 0 1rem 0;
font-weight: 600;
line-height: 1.2;
}
p {
margin: 0 0 1rem 0;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
`}</style>
)
}
4. Sass/SCSS Support
Installing Sass:
npm install sass
SCSS Variables and Mixins:
// styles/variables.scss
$primary-color: #0070f3;
$secondary-color: #f0f0f0;
$text-color: #333;
$background-color: #fff;
$border-radius: 4px;
$spacing-unit: 8px;
// Breakpoints
$mobile: 768px;
$tablet: 1024px;
$desktop: 1200px;
// Mixins
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin button-base {
padding: 12px 24px;
border: none;
border-radius: $border-radius;
cursor: pointer;
font-size: 16px;
transition: all 0.2s ease;
}
@mixin responsive($breakpoint) {
@if $breakpoint == mobile {
@media (max-width: $mobile) {
@content;
}
}
@if $breakpoint == tablet {
@media (max-width: $tablet) {
@content;
}
}
@if $breakpoint == desktop {
@media (min-width: $desktop) {
@content;
}
}
}
Using SCSS in Components:
// components/Header.module.scss
@import '../styles/variables.scss';
.header {
background: $background-color;
border-bottom: 1px solid $secondary-color;
padding: $spacing-unit * 2;
@include flex-center;
justify-content: space-between;
@include responsive(mobile) {
padding: $spacing-unit;
flex-direction: column;
gap: $spacing-unit;
}
}
.logo {
font-size: 1.5rem;
font-weight: 700;
color: $primary-color;
text-decoration: none;
}
.nav {
display: flex;
gap: $spacing-unit * 3;
@include responsive(mobile) {
gap: $spacing-unit * 2;
}
}
.navLink {
color: $text-color;
text-decoration: none;
font-weight: 500;
transition: color 0.2s ease;
&:hover {
color: $primary-color;
}
&.active {
color: $primary-color;
font-weight: 600;
}
}
5. Tailwind CSS Integration
Installing Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Tailwind Configuration:
// tailwind.config.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: {
colors: {
primary: {
50: '#eff6ff',
500: '#3b82f6',
900: '#1e3a8a',
},
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
},
},
},
plugins: [],
}
Using Tailwind CSS:
// components/TailwindCard.js
export default function TailwindCard({ title, children, variant = 'default' }) {
const baseClasses = "bg-white rounded-lg shadow-md p-6 transition-shadow duration-200"
const variantClasses = {
default: "hover:shadow-lg",
primary: "bg-primary-50 border-l-4 border-primary-500",
success: "bg-green-50 border-l-4 border-green-500",
}
return (
<div className={`${baseClasses} ${variantClasses[variant]}`}>
<h3 className="text-xl font-semibold text-gray-900 mb-4">{title}</h3>
<div className="text-gray-600">{children}</div>
</div>
)
}
6. CSS-in-JS with Styled Components
Installing Styled Components:
npm install styled-components
npm install -D babel-plugin-styled-components
Babel Configuration:
// .babelrc
{
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true
}
]
]
}
Using Styled Components:
// components/StyledButton.js
import styled, { css } from 'styled-components'
const Button = styled.button`
padding: 12px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
font-weight: 500;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
justify-content: center;
${props => props.variant === 'primary' && css`
background-color: #0070f3;
color: white;
&:hover {
background-color: #0051cc;
transform: translateY(-1px);
}
`}
${props => props.variant === 'secondary' && css`
background-color: #f0f0f0;
color: #333;
&:hover {
background-color: #e0e0e0;
}
`}
${props => props.size === 'large' && css`
padding: 16px 32px;
font-size: 18px;
`}
${props => props.size === 'small' && css`
padding: 8px 16px;
font-size: 14px;
`}
${props => props.disabled && css`
opacity: 0.6;
cursor: not-allowed;
&:hover {
transform: none;
}
`}
`
export default function StyledButton({ children, ...props }) {
return <Button {...props}>{children}</Button>
}
Advanced Styling Techniques
1. CSS Custom Properties (CSS Variables)
/* styles/globals.css */
:root {
--primary-color: #0070f3;
--secondary-color: #f0f0f0;
--text-color: #333;
--background-color: #fff;
--border-radius: 4px;
--spacing-unit: 8px;
--font-size-base: 16px;
--font-size-lg: 18px;
--font-size-sm: 14px;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
}
/* Dark mode */
[data-theme="dark"] {
--text-color: #fff;
--background-color: #000;
--secondary-color: #1a1a1a;
}
// components/ThemeProvider.js
import { createContext, useContext, useEffect, useState } from 'react'
const ThemeContext = createContext()
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
setTheme(savedTheme)
}
}, [])
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme)
localStorage.setItem('theme', theme)
}, [theme])
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light')
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}
export const useTheme = () => useContext(ThemeContext)
2. Responsive Design
/* styles/responsive.css */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
.grid {
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
/* Mobile First Approach */
@media (min-width: 768px) {
.container {
padding: 0 40px;
}
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 1200px) {
.container {
padding: 0 60px;
}
}
3. Animation and Transitions
/* styles/animations.css */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.fade-in {
animation: fadeIn 0.5s ease-out;
}
.slide-in {
animation: slideIn 0.3s ease-out;
}
.hover-lift {
transition: transform 0.2s ease;
}
.hover-lift:hover {
transform: translateY(-2px);
}
Best Practices
1. CSS Organization
/* ✅ Good: Organized CSS structure */
/* 1. Reset and base styles */
/* 2. Variables and mixins */
/* 3. Layout styles */
/* 4. Component styles */
/* 5. Utility classes */
/* 6. Media queries */
2. Performance Optimization
// ✅ Good: Lazy load CSS
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <div>Loading...</div>,
ssr: false
})
3. CSS-in-JS Best Practices
// ✅ Good: Memoized styled components
import { memo } from 'react'
import styled from 'styled-components'
const StyledButton = styled.button`
/* styles */
`
export default memo(StyledButton)
Common Mistakes to Avoid
1. CSS Specificity Issues
/* ❌ Wrong: High specificity */
div.container .content .text {
color: red;
}
/* ✅ Correct: Lower specificity */
.text {
color: red;
}
2. Inline Styles Overuse
// ❌ Wrong: Too many inline styles
<div style={{ color: 'red', fontSize: '16px', margin: '10px' }}>
// ✅ Correct: Use CSS classes
<div className="text-red text-base m-2">
3. Missing CSS Reset
/* ❌ Wrong: No CSS reset */
/* Browser default styles cause inconsistencies */
/* ✅ Correct: Include CSS reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
Summary
Next.js provides flexible styling options to suit different project needs:
- Global CSS for base styles and variables
- CSS Modules for component-scoped styles
- Styled JSX for dynamic styling
- Sass/SCSS for enhanced CSS features
- CSS-in-JS for component-based styling
- Utility frameworks like Tailwind for rapid development
Key Takeaways:
- Choose the right styling approach for your project
- Use CSS variables for theming and consistency
- Implement responsive design from the start
- Optimize for performance with code splitting
- Follow consistent naming conventions
This tutorial is part of the comprehensive Next.js learning path at syscook.dev. Continue to the next chapter to learn about data fetching and API integration.
Author: syscook.dev
Last Updated: December 2024