Next js

Styling in Next.js

1. Global CSS

  • You can import global CSS files inside your custom _app.js.

  • Example:

js
// pages/_app.js
import '../styles/global.css';

export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}

  • Note: Global CSS can only be imported here, not in individual components or pages.


2. CSS Modules

  • Scoped CSS to a single component to avoid naming conflicts.

  • Filename: Component.module.css

Example:

css
/* styles/Button.module.css */
.button {
background-color: blue;
color: white;
padding: 10px;
}
jsx
// components/Button.js
import styles from '../styles/Button.module.css';

export default function Button() {
return <button className={styles.button}>Click me</button>;
}


3. Sass / SCSS

  • Next.js supports Sass out of the box.

  • Install Sass:

bash
npm install sass
  • Use .scss or .sass files as global or modules.

Example with SCSS module:

scss
/* styles/Header.module.scss */
.title {
color: red;
font-size: 24px;
}
jsx
import styles from '../styles/Header.module.scss';

export default function Header() {
return <h1 className={styles.title}>Hello Sass</h1>;
}


4. Styled JSX (Built-in CSS-in-JS)

  • Next.js includes Styled JSX for scoped styles inside components.

Example:

jsx
export default function Message() {
return (
<>
<p>Hello styled JSX!</p>
<style jsx>{`
p {
color: green;
font-weight: bold;
}
`}</style>
</>
);
}

5. Using CSS-in-JS Libraries

  • You can use libraries like styled-components, Emotion, or Stitches.

  • Requires additional setup for server-side rendering.

Example with styled-components:

bash
npm install styled-components
jsx
import styled from 'styled-components';

const Title = styled.h1`
color: purple;
font-size: 2rem;
`
;

export default function Home() {
return <Title>Styled Components in Next.js</Title>;
}


6. Tailwind CSS

  • Utility-first CSS framework popular with Next.js.

  • Easy to configure with Next.js for rapid styling.

Setup summary:

bash
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure tailwind.config.js and import Tailwind styles globally.


Summary Table

Styling Method Description When to Use
Global CSS Site-wide styles Base styles, resets
CSS Modules Scoped CSS per component Avoid naming collisions
Sass/SCSS Extended CSS with variables, nesting Larger projects needing structure
Styled JSX Inline scoped CSS inside components Simple component-level styles
CSS-in-JS (styled-components, Emotion) JS-based styling with dynamic props Complex styles, theming
Tailwind CSS Utility-first CSS framework Rapid UI building with utility classes

Leave a Reply

Your email address will not be published. Required fields are marked *