Tag: Module 4: Styling in Next.js

  • Module 4: Styling in Next.js

    Lesson 1: CSS Modules

    CSS Modules provide a scoped and modular approach to styling your components. By using CSS Modules, you avoid naming conflicts and ensure styles are applied only where intended.

     How to Use:

    1. Create a CSS file with the .module.css extension (e.g., styles/Home.module.css ).
    2. Import it into your component:

    import styles from ‘./Home.module.css’;

    export default function Home() {
    return <h1 className={styles.title}>Welcome to Next.js</h1>;
    }

    extension (e.g., styles/Home.module.css ).

    1. The imported styles object maps class names to unique identifiers.

    Advantages:

    • Automatic scoping of CSS.
    • No need to worry about global namespace pollution.

    Lesson 2: Styled JSX

    Styled JSX is a built-in CSS-in-JS solution provided by Next.js. It allows you to write scoped styles directly within your components.

    How to Use:

    export default function Home() { return (

    <h1>Welcome to Next.js</h1>

    );
    }

    Features:

    •  Scoped styles ensure no CSS leakage.
    •  Dynamic styles can use JavaScript variables.

    Dynamic Styling Example:

    export default function Home() { const isActive = true;
    return (

    <h1>Welcome</h1>

    );
    }

    Lesson 3: Integrating Tailwind CSS

    Tailwind CSS is a utility-first CSS framework that can be easily integrated with Next.js for rapid styling.

     Installation Steps:

    1. InstallTailwind CSS and its dependencies:

    npm install -D tailwindcss postcss autoprefixer
    npx tailwindcss init

    1. Configure tailwind.config.js to enable JIT mode and specify content paths:

    module.exports = {
    content: [‘./pages/**/*.{js,ts,jsx,tsx}’, ‘./components/**/*.{js,ts,jsx,tsx}’], theme: {
    extend: {},
    },
    plugins: [],
    };

    1. AddTailwind to your global CSS file (e.g., styles/globals.css ):

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

    1. Importthe global CSS file in pages/_app.js :

    import ‘../styles/globals.css’;

    function MyApp({ Component, pageProps }) { return ;
    }

    export default MyApp;

    Advantages:

    • Rapid prototyping with utility classes.
    • Fully customizable design system.

    Additional Resources

    Styling  Guide