/

Styling Next.js components using CSS

Styling Next.js components using CSS

In Next.js, we have the freedom to choose any library for styling React components. However, Next.js comes with its own built-in library called styled-jsx which offers scoped CSS. This allows us to write CSS that only affects the specific component it is applied to, making it easier to maintain.

To add CSS to a React component in Next.js, we need to insert it inside a <style jsx> block in the JSX code. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
const Index = () => (
<div>
<h1>Home page</h1>

<style jsx>{`
h1 {
font-size: 3rem;
}
`}</style>
</div>
);

export default Index;

We simply write plain CSS inside the <style jsx> block, just like we would in a regular .css file. It’s also possible to use interpolation inside the block to dynamically change the CSS values based on props or other variables.

To apply CSS globally, not scoped to a component, we can use the global keyword in the <style jsx> tag. For example:

1
2
3
4
5
<style jsx global>{`
body {
margin: 0;
}
`}</style>

If you want to import an external CSS file in a Next.js component, you will need to install the @zeit/next-css package first:

1
npm install @zeit/next-css

Next, create a configuration file called next.config.js in the project root directory with the following content:

1
2
const withCSS = require('@zeit/next-css');
module.exports = withCSS();

Now, you can import CSS files just like you would with JavaScript libraries or components:

1
import '../style.css';

Alternatively, if you prefer using SASS, you can use the @zeit/next-sass library instead.

To summarize, Next.js provides the styled-jsx library for styling React components with scoped CSS. However, you can also use external CSS files by installing and configuring the @zeit/next-css package.

tags: [“Next.js”, “CSS styling”, “styled-jsx”, “global styling”, “external CSS files”]