Adding Tailwind CSS to a Gatsby project
Tags: gatsby, css, tutorial
Published: 2020-08-06 06:50:36

There are two types of people in this world: those who don’t put a case on their phone and those who put a case, side load apps, run beta versions of an unreleased OS, jailbreak their device **and** *accept tracking cookies.* 😬 Cookies aside, sometimes you just need a little customisation to get the most out of something. The same can be said for styling web apps. CSS frameworks like Bulma & Bootstrap give you some awesome styles out of the box, but that’s what your stuck with. If you’re tasked with creating something truly unique, surely there’s another way than just writing 100s of lines of CSS code yourself?

## Introducing Tailwind CSS
Yes, it’s another framework, but there is a significant difference with this one. Tailwind works under the basis of “utility classes”. For example, rather than giving you a pre-defined `button` class which would style your buttons, you can group together a bunch of low-level classes which would render out any kind of button you can think of. Something like this:

```html
<button class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
	Green button
</button>
```

Conversely, with Bulma for example, you’re likely doing something like this:

```html
<button class="button">
	Simples.
</button>
```

*“Multiple classes instead of a simple, single class? Hogwash I say!”*

True. At first it looks a little dicey and completely against the standard way of writing HTML and CSS. Luckily for us, Tailwind also allows you to extract commonly used classes into component classes. So we can get back to our beloved way of writing the web:

```html
<button class="btn btn-green">
	Green button
</button>

<style>
	.btn {
		@apply font-bold py-2 px-4 rounded;
	}

	.btn-green {
		@apply bg-green-500 text-white;
	}

	.btn-green:hover {
		background: #2F855A;
	}
</style>
```

(Lol, those styles can also exist in a CSS file if you want — more on that later…)

The `@apply` directive allows us to use Tailwind classes in CSS (really useful if you’ve defined some extra custom stuff in your config), but you can also mix and match with traditional CSS.

## Adding to Gatsby
Now we’ve got an idea of what Tailwind is and how it works, let’s add it to a Gatsby project. We’ll be using Tailwind via PostCSS, but other methods are available. If you want to find out more, visit the [Gatsby docs](https://www.gatsbyjs.org/docs/tailwind-css/). You’ll need a Gatsby project to follow along with. If you don’t have one yet, just run these commands in your terminal to get started:

```bash
yarn global add gatsby-cli	# install gatsby-cli globally
gatsby new gatsby-site		# create a new site
cd gatsby-site				# change into our newly created site's directory
```

Now we’re ready! 🔥💪🏾
Firstly, let’s install the additional dependencies we’re going to need in our project:

```bash
yarn add gatsby-plugin-postcss tailwindcss
```

(If you’re rocking npm, replace those yarn commands above with the following: `npm install -g gatsby-cli` & `npm install gatsby-plugin-postcss tailwindcss`)

We’re using PostCSS so we can use the `@tailwind` directives in our CSS files, alongside all the other directives — like `@apply` mentioned previously.

Go ahead and add the PostCSS plugin into your `gatsby-config.js` file:

```js
// gatsby-config.js 

module.exports = {
	plugins: [
		`gatsby-plugin-postcss`,
	]
}
```

Now create a `postcss.config.js` file in the root of your project. This is where we’ll include our reference to Tailwind:

```js
// postcss.config.js

module.exports = () => {
	return {
		plugins: [require('tailwindcss')]
	}
}
```

Now we just need to include the Tailwind directives in our CSS file, giving us access to all of that utility first goodness! 🤤

Open up `layout.css` (should be located in:`src/components` if not, create it and import it in your app’s layout component ). That’s a lot of CSS in there! We can leave this as it is for now, but we need to add some things around it. Begin by adding `@tailwind base;` in the very first line of the file. Then underneath that *mountain* of CSS code, add `@tailwind components;` . Finally, underneath that, add `@tailwind utilities;`. So you should have something like this:

```css
/* src/components/layout.css */

@tailwind base;

html {
	font-family: sans-serif;
	-ms-text-size-adjust: 100%;
	-webkit-text-size-adjust: 100%;
}

/* ...the rest of the element styles... */

@tailwind components;

.heading {
	@apply font-bold text-4xl; /* a heading with bold font and 2.25rem font size */
}

@tailwind utilities;
```

Let’s go over those directives!
- `@tailwind base` -- adds base styles offered by Tailwind and any additional plugins, alongside boilerplate CSS
- `@tailwind components` -- adds component classes from Tailwind and any additional plugins
- `@tailwind utilities` -- adds utility classes from Tailwind and, of course, any additional plugins

You’ll notice I’ve also sneaked in a cheeky custom component class there called `heading`. This is just to demonstrate how easy it is to add reusable component classes in your CSS. Now everything’s installed and configured, let’s use it!

## Using Tailwind
This. Is. Easy. Make a new file in your pages directory called `demo.js` and add the following code to it:

```js
// src/pages/demo.js

import React from "react"

import Layout from "../components/layout"
import SEO from "../components/seo"

const DemoPage = () => (
    <Layout>
        <SEO title="Tailwind Demo" />
        <h1 className="heading">What's up, my people!</h1>
        <p className="tracking-wide">Ain't this sweet?</p>
        <button className="font-bold py-2 px-4 rounded bg-green-500 text-white hover:bg-green-700 block mb-8">Yaaassssss!</button>
        <h2 className="inline-block md:hidden text-xl">Small screen size (full width paragraph)</h2>
        <h2 className="hidden lg:hidden md:inline-block text-xl">Medium screen size (3/4 width paragraph)</h2>
        <h2 className="hidden lg:inline-block text-xl">Large screen size (1/2 width paragraph)</h2>
        <p className="w-full md:w-3/4 lg:w-1/2">
            Look at me! I am a really long paragraph to demonstrate how Tailwind handles responsive layouts. Unfortunately, I have run out of things to say so will now revert to everyone's favourite: <a className="font-bold underline" href="https://baconipsum.com/">Bacon Ipsum!!!!</a> Bacon ipsum dolor amet tail beef ribs prosciutto tenderloin. Leberkas brisket sausage landjaeger shoulder filet mignon. Chislic tail andouille strip steak, short loin turducken pork leberkas prosciutto burgdoggen sausage alcatra bresaola tongue. Kielbasa turkey tongue ground round meatloaf venison.
        </p>
    </Layout>
)

export default DemoPage

```

As you can see, in the `className`  props, we’re just adding Tailwind classes, alongside our custom `heading` class we created earlier. Run `gatsby develop` in your terminal and navigate to [localhost:8000/demo](http://localhost:8000/demo) in your browser to see what it looks like. Try resizing your screen to see some pseudo responsiveness in action!

With our simple demo, we’ve only just scratched the surface of what we can do with Tailwind. [Their documentation](https://tailwindcss.com/docs/installation/) is the best place to go to understand what other classes and styles are available, as well as information on how to utilise Flexbox and grids to achieve some modern, responsive layouts.

## Customising
Let’s say you really wanted to up your customisation game and include your own colours, container styles and more. Well, it’s pretty straightforward to do that with Tailwind, but we do need to set up some more configurations. In the root of your project, create a new file called: `tailwind.config.js` and enter the following:

```js
// tailwind.config.js

module.exports = {
    purge: [
        './src/**/*.js',
        './src/**/*.tsx',
    ],
    theme: {
        container: {
            center: true,
            padding: {
                default: '1rem',
                sm: '2rem',
                lg: '3rem',
                xl: '4rem',
            },
        },
        extend: {
            colors: {
                primary: '#de7261',

            },
            height: {
                '1/4': '25vh',
                '1/3': '33vh',
                '1/2': '50vh',
                '3/4': '75vh',
                'in': 'inherit',
            },

            fontSize: {
                '7xl': '5rem',
                '8xl': '6rem',
            }
        },
    },
}
```

The code above is telling Tailwind that we’d like to modify our theme by allowing container styles (otherwise disabled by default) and extending the colour, height and fontSize options with some new values. This theme section is where we can define a custom colour palette, fonts families, breakpoints — everything related to the visual style and design. With the options above, we can now use `bg-primary` , `h-3/4` and `text-7xl` throughout our site’s styles wherever we want! (As well as similar classes for the other options.)

Also notice the purge bit at the top of the file. This means our final compiled CSS (in production builds only) will be stripped of all the styles that we didn’t use, minimising the size of our overall app.

Try adding some of these new classes into any page of your project or extend the config further to create your own styles and watch something truly unique come to life!

(You’ll probably need to restart your dev server to see the changes take place!)

## Further reading
Like I said we’re only just scratching the surface with Tailwind here. Once you get the hang of it, it’s pretty easy to create cards, landing page heroes, forms and everything else one of those other frameworks could do. The difference being, it’s your own totally unique style!

If you want to read some more, the following links will come in handy:

[Tailwind Docs](https://tailwindcss.com/docs/installation/) — Official documentation from Tailwind  
[Adding Tailwind to Gatsby via CSS-in-JS](https://www.gatsbyjs.org/docs/tailwind-css/#option-2-css-in-js) — Instructions on installing Tailwind to use with CSS-in-JSS library, Emotion  
[Tailwind UI](https://tailwindui.com/) — Pre-built components made by the people who made Tailwind  
[Configuring Tailwind](https://tailwindcss.com/docs/configuration/) - A guide to configuring Tailwind  

The full source code for this demo is available on my [GitHub](https://github.com/tundeio/gatsby-tailwind-demo).  
✌🏾

---

<small>*“Err, what’s up with the random dog???”*</small>  
<small>It has a **tail** … I’ll see myself out.</small>