April 25, 2020
Update (5/2/2020): Added another bonus section about how to implement dark mode with Tailwind.
Update (12/17/2020): Added a note about the
purge
config intailwing.config.js
When creating the site for Fluency, I figured now was as good a time as any to try out Tailwind CSS. Like all static sites I build nowadays, the site runs on Gatsby, but unfortunately the docs on how to integrate Tailwind with Gatsby are quite complicated. As someone who isn't super familiar with the current state of web build systems, PostCSS, etc, it took me longer than I thought to figure out how to integrate it.
So, this is what I know as the minimal number of steps to start using Tailwind classes to style your CSS in a Gatsby site:
npm install tailwindcss --save-dev
npm install --save gatsby-plugin-postcss
gatsby-config.js
, so that Gatsby knows to load postcss (which loads Tailwind):
plugins: [`gatsby-plugin-postcss`],
postcss.config.js
so that postcss knows to load Tailwind:
module.exports = () => ({
plugins: [require("tailwindcss")]
});
global.css
:
@tailwind base;
@tailwind components;
@tailwind utilities;
gatsby-browser.js
, so that Gatsby imports Tailwind on every page:
import "./src/global.css";
Voila, you should now be able to use Tailwind classes anywhere to style your site.
If you happen to use the Tailwind CSS Itellisense plugin for VS Code, which will autocomplete Tailwind CSS classes, there's an issue open indicating that a Tailwind config is required. In order to make this work, you'll need to run
npx tailwind init
Update (9/20/2023): Tailwind now supports dark mode out of the box! See Tailwind Docs for info on how to use it - this section is now outdated.
~I loved this article from Stefan Zweifel about how to support dark mode in Tailwind: if you've already got a config file from the last step (tailwind init
), then you can copy this config to support dark mode out of the box:~
// tailwind.config.js
module.exports = {
purge: ["./src/**/*.jsx"],
theme: {
extend: {},
screens: {
sm: "640px",
md: "768px",
lg: "1024px",
xl: "1280px",
"dark-mode": { raw: "(prefers-color-scheme: dark)" }
}
},
variants: {},
plugins: []
};
~Then you can use dark-mode
as a specifier for your Tailwind styles: dark-mode:text-white
for example.~
~(Note: I've included the built-in screens for Tailwind here, since if you just put in the dark-mode
specifier, other screens like md
won't work. I'm not sure if there's a way to extend the default configuration rather than redefining it.)~
~(Also note: you'll need to include the purge
configuration so your generated files aren't huge in accordance with the Tailwind recommendation.)~
I'm Noah, a software developer based in the San Francisco Bay Area. I focus mainly on full stack web and iOS development