DEV Community

Cover image for Next js 14 First day - Styling in Next js
Mohammed Ramadan
Mohammed Ramadan

Posted on

Next js 14 First day - Styling in Next js

There are 3 ways to style component :
1- CSS modules
2- Global
3- library like Tailwind


CSS Modules

  1. File has extension .module.css
  2. import the file in the page component
//page.js

import styles from "./page.module.css";

export default function Home() {
  return (
    <div>
      <h1 className={styles.title}>Hello world!!</h1>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode
//page.module.css
.title{
  font-size: 36px;
}
Enter fullscreen mode Exit fullscreen mode

Global

  • You can import global.css in any file, but it’s good practice to add it in top level component like : layout.js.
  • It’s used to add CSS rules to all routes in your application such as CSS reset-rules….. etc.

Tailwind

First install Tailwind in your app

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

Now configure tailwind in your app by adding paths to your files in tailwind.config.js.

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}', 
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',

  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Import your tailwind css directive in your global file globals.css

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Now, add some classes to your element to test

export default function Home() {
  return (
    <div>
      <h1 className="text-3xl font-bold underline">Hello world!!</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

⚠ If you have a struggle with it and tailwind classes doesn’t show in your app try to close your app and run it again by : npm run dev

Top comments (0)