Download the template for this blog from Github

Next.js / Ghost Tutorial: 4 - Styling with Vanilla CSS and Tailwind

In the last post on this series, we created a Next.js project and (hopefully) ended up with a working application. For now, it doesn't do anything besides greeting the visitors, but we are about to change that.

In this episode, we'll add some style.


When it comes to styling your application, there is plenty of options available.

Global styling

In Next.js, global styles - such that can be attached to all pages and components - must be imported through a special file named "_app.js" located in the "/pages" folder of the project.


First, create a new top level folder named "/styles" and place a new file named "globalstyles.css" in it.

/* file: /styles/globalstyles.css */

h1 {
    color: red;
}

Let's now create _app.js and import the newly created .css file:

// file: /pages/_app.js

import '../styles/globalstyles.css'

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

export default MyApp

Note that we are using a relative path here.

To quick test this rule, change the file index.js to:

function Home() {
  return (
    <>
      <h1>My Blog</h1>
      <div>Welcome at ghost next.js tutorial</div>
    </>
  )
}

export default Home

My Blog should now show up in red.


Tip: for changes to _app.js to take effect, you need to restart your dev server (CTRL+C followed by npm run dev)

Component-level styling

Besides defining global styles, you can also opt to use component-based styles.
The main reason for doing so might be to scope css styles to component/page level. This way, each component gets a standalone style without you having to worry about CSS class name collisions.


You define a component-level style by creating a css file named after the schema: "componentname.module.css"

Let me show that with the Home component, the only one we have in our project so far.


Create a file named Home.module.css in the /styles folder (you can put the file in another location too, as long as you import it from there later):

/* file: /styles/Home.module.css */ 

h2.caption { 
  color: darkviolet; 
  margin-left: 20px; 
  text-decoration: underline; 
}

Next, modify index.js to:

import styles from '../styles/Home.module.css'

function Home() {
  return (
    <>
      <h1>My Blog</h1>
      <h2 className={styles.caption}>Checking module style here</h2>
      <div>Welcome at ghost next.js tutorial</div>
    </>
  )
}

export default Home

With the first line we import our component level styles and store them in the styles variable.
Then, on line 7, we insert a <h2> tag and assign it to the css class caption.


That's it!

To learn more about component level css, check the Next.js documentation (see the section "Further reading" at the end of this article).


It is probably a good time to commit the changes to the previously created git repository.

git add .
git commit -m "Added styles"
git push

Styling with Tailwind CSS

Besides global and component level css, you may also use one of the may existing css frameworks to style your Next.js application.

In this tutorial, I will show you how to use Tailwind CSS, one of the major CSS frameworks currently available that integrates very well with Next.js


Let's start by installing it via npm. In a command line at the top folder of your project, enter:

npm install tailwindcss postcss autoprefixer

If all goes well, you will now have three new dependencies in your package.json file (package versions may differ on your system):

package_json_dependencies1

Tailwind CSS and postcss have their own configuration files.
Create them with the following command:

npx tailwindcss init -p

This will generate the following two files:


tailwind.config.js

// tailwind.config.js

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

postcss.config.js

// postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

By default, Tailwind imports a whole set of CSS classes, most of which you will probably never use in your project.
To avoid dragging these along with your production application, Tailwind has built-in functionality to reduce the size of your code by stripping out all unused classes, greatly improving performance.

This technique is known as tree-shaking

All you need to do is specify which code files should be searched for style classes to keep. Open the configuration file tailwind.config.js and replace the line:

purge: []

with:

purge ['./pages/**/*.js', './components/**/*.js'],

Next, create a new css file /styles/tailwind.css to import Tailwind's styles:

/* /styles/tailwind.css    */

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

Tip: this file can be named differently but I prefer to use "talking names" so their purpose is clear.


Finally, we need to import the just created css file into our code by adding the following line at the top of the existing file _app.js:

import '../styles/tailwind.css'

The complete file should now look like this:

import '../styles/tailwind.css' // <-- new
import '../styles/globalstyles.css'

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

export default MyApp

For the changes to take effect, switch to the command line and type:

npm run dev

(in case the development server is still running, interrupt it with CTRL+C first).

Using your browser dev tools, you can see that the index page is already getting some basic styles from tailwind.css:

devtools_tailwind

To explicitly use a style class, modify the <div> like this:

<div className="bg-red-600"">Welcome at Ghost Next.js awesome tutorial</div>

Refresh your browser and you should see the text with a red background.

It is now a good time to commit the changes to your code repository:

git add .
git commit -m "Added Tailwind css"
git push

Recap

We have seen three different methods to style our application, which can even be combined with each other:

  • global styles
  • component-level styles
  • Tailwind CSS

Further reading


Filipe Matos