From b51dc543c8e4034f7b4712c632cbcd2e5419384a Mon Sep 17 00:00:00 2001 From: Kid <44045911+kidonng@users.noreply.github.com> Date: Tue, 17 Jun 2025 14:04:39 +0800 Subject: [PATCH 1/2] Add custom variant as an alternative --- docs/when-and-how-to-use-it.md | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/when-and-how-to-use-it.md b/docs/when-and-how-to-use-it.md index ca5e30aa..fdf549af 100644 --- a/docs/when-and-how-to-use-it.md +++ b/docs/when-and-how-to-use-it.md @@ -160,6 +160,41 @@ function join(...args) { The main downside of this approach is that it only works one level deep (you can't override the `bg-red-500!` class in the example above). But if you don't need to be able to override styles through multiple levels of composition, this might be the most lightweight approach possible. + +### Using Tailwind's custom variant + +Instead of increasing specificity with important modifier, you can also decrease specificity of base classes using Tailwind's [custom variant](https://tailwindcss.com/docs/adding-custom-styles#adding-custom-variants). + +For example, you can create a custom variant that wraps the selector with [`:where()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:where): + +```css +@custom-variant component (:where(&)); +``` + +And use the variant in the component's base classes: + +```jsx +// React components with JSX syntax used in this example + +function MyComponent() { + return ( + <> + + // .bg-red-500 works as expected since it has higher specificity + + + ) +} + +function Button({ className ...props }) { + return - // .bg-red-500 works as expected since it has higher specificity + {/* .bg-red-500 works as expected since it has higher specificity */} )