Back to Next JS Course

Next JS Course

Styling in Next JS can be approached in various ways, providing flexibility and options based on the needs of your application.

Global Styles

Using a Global CSS File: You can include global styles by importing a CSS file in your custom _app.js file.

For example,

styles/globals.css

body { font-family: Arial, sans-serif; margin: 0; padding: 0; }

_app.js

import '../styles/globals.css'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp;

CSS Modules

Scoped CSS

CSS Modules allow you to scope CSS to a specific component to avoid class name collisions.

components/Button.module.css

.button { background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }

Using in a component

import styles from './Button.module.css'; const Button = ({ text }) => { return <button className={styles.button}>{text}</button>; }; export default Button;

Styled-JSX

Scoped CSS-in-JS

Styled-JSX is built into Next.js and allows you to write scoped CSS directly in your components.

const Button = ({ text }) => { return ( <div> <button className="button">{text}</button> <style jsx>{` .button { background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; } `}</style> </div> ); }; export default Button;

CSS-in-JS Libraries

Styled Components

A popular CSS-in-JS library that allows you to style components with ES6 template literals.

Installation npm install styled-components

import styled from 'styled-components'; const Button = styled.button` background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; `; const App = () => { return <Button>Click Me</Button>; }; export default App;

Tailwind CSS

Utility-First CSS Framework

Tailwind CSS provides utility classes to rapidly build custom designs.

Installation

npm install tailwindcss npx tailwindcss init

Configuration: tailwind.config.js

module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], }
const Button = () => { return ( <button className="bg-blue-500 text-white py-2 px-4 rounded"> Click Me </button> ); }; export default Button;

Global Styles with Styled-JSX

Adding Global Styles: Styled-JSX also supports global styles.

const MyApp = ({ Component, pageProps }) => { return ( <> <Component {...pageProps} /> <style jsx global>{` body { font-family: Arial, sans-serif; margin: 0; padding: 0; } `}</style> </> ); }; export default MyApp;