Tailwind after 1 month of use
Photo by Jordan LadikosI've written about tailwind before
This is my experience after 1 month using tailwind extensively.
What and how #
- Write css properties directly as a class name using shorthands.
- It generates hundreds (thousands?) of class names to cover all possible properties.
- Shorthands are generated using a configuration file (theme) and a tool called postcss
Things I liked #
- Never specify a size or a property by value. Always by reference (the theme). Easier to make consistent design
- No need to create a style system for the whole app. No need to invent or learn new class names.
- Very easy way to create reponsive designs
- Good alternative for style as a function of state (aka CSS in JS) in frameworks like Angular or React
- Efficient: include the classes you need (not tailwind specific, but a side effect if used as they recommend)
- Faster development? (when you know the shorthand names)
Things I didn't like #
- Ugly. Extremely large class names. I'm getting used to it.
- Need to learn the shortnames of the css properties (although documentation is great)
- You lose the "cascade" of the css (not a real problem in SPA, I think)
Show me the code #
1. Install dependencies #
We need:
- tailwind (library)
- postcss (library and cli)
- postcss plugins
npm install --dev \
postcss postcss-cli \
tailwindcss \
postcss-import postcss-purgecss autoprefixer nano @fullhuman/postcss-purgecss
2. Generate the tailwind theme #
npx tailwindcss init --full
3. Postcss configuration #
postcss.config.js
:
const purgecss = require("@fullhuman/postcss-purgecss")({
content: ["./src/**/*.tsx"],
css: ["./src/styles/index.css"],
});
const cssnano = require("cssnano")({
preset: "default",
});
const isProd = process.env.NODE_ENV === "production";
module.exports = {
plugins: [
require("postcss-import"),
require("tailwindcss"),
require("autoprefixer"),
isProd && purgecss,
isProd && cssnano,
],
};
4. Create the source stylesheet #
src/styles/tailwind.css
:
@tailwind base;
@tailwind components;
@tailwind utilities;
5. Generate the css #
package.json
:
{
"scripts": {
"css:watch": "postcss --watch src/styles/tailwind.css -o src/styles/index.css",
"css:dev": "postcss src/styles/tailwind.css -o src/styles/index.css",
"css:prod": "postcss src/styles/tailwind.css -o src/styles/index.css --env production"
}
}
6. Usage #
React example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles/index.css";
const App: React.FC = () => {
const isBlue = Math.random() < 0.5;
return (
<button
className={`font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded ${
isBlue
? "bg-blue-300 hover:bg-blue-700 text-blue-700"
: "bg-orange-300 hover:bg-orange-700 text-orange-700"
}`}
>
ClickMe!
</button>
);
};
const root = document.getElementById("root");
ReactDOM.render(<App />, root);