Tailwind is a great solution for styling your application but it’s not always straightforward.
Good to know#
Dark & light themes#
Tailwind provides a way to specify dark color with the dark: prefix (cf the official doc ↗) but it doesn’t document how to have color variable that automatically switch between 2 values. Here is how you can do it:
/* The light value of the color is attached to the body (and host for web-component) */
:root, :host {
--background-button: #f8fafc;
}
/* The dark value of the color is attached to the dark class selector */
.dark {
--background-button: #141516;
}
/* You use the `--color` prefix to make the tailwind compilation work */
@theme inline {
--color-background-button: var(--background-color);
}cssWith that in place you should be able to use the color like this in your react component:
const MyButton = () => {
return <button className="bg-background-button">Test</button>
}jsxReset colors#
If you want to completely reset colors, meaning you don’t only want to override the value of existing tailwind color, use this --color-*: initial pattern:
@theme inline {
--color-*: initial;
/* Define your colors here */
}cssYou can force tailwind to compile variables#
By default, tailwind strip everything that is not used in a classname but you might want to still compile some regardless of the usage if you want to distribute a package with specific variables. The static directive is meant for that
@theme static {
--spacing: 4px;
}cssScope preflight#
If you’re adding tailwind in an existing codebase, you might want to run preflight just for a subset of your DOM. You can do so with this approach (taken from here ↗):
@layer theme {
@import 'tailwindcss/theme.css';
}
@layer base {
[data-twp] {
@import 'tailwindcss/preflight.css';
}
[data-twp-reset] {
*,
::after,
::before,
::backdrop,
::file-selector-button {
all: revert-layer;
}
}
}
@layer components;
@layer utilities {
@import 'tailwindcss/utilities.css';
}cssThe preflight will be active only for the element (and its children) with data-twp attribute is present.
Use cva (Class Variance Authority)#
You will quickly feel the need to have variant for your component. It’s appear shadcn way of using cva library is pretty flexible.
Traps to avoid#
Don’t use tailwind classes from another package#
It might seems obvious if you’re deep into tailwind but don’t forget to document and communicate to other devs that they shouldn’t use the class that has been compiled from another package as it might disappear in the next version of this package.
Use :host for web-components#
Lots of example are built with :root selector only but if you want to declare style inside a web-component, you will also need :host.
:root, :host {
/* ... */
}css