Insane idea to give components *overridable* default TW classes #3523
richardtallent
started this conversation in
Ideas
Replies: 1 comment
-
Update: The plugin I wrote for this didn't work 100% of the time, because the specificity of So, I went the opposite direction and created a plugin variant https://github.com/richardtallent/tailwindcss-override |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm converting some components over to Tailwind. Easy enough:
When when I use those components, sometimes I want to override portions of their default style. This can't be done with Tailwind classes reliably, since all classes having the same CSS selectivity score, which means whichever class is last in the Tailwind CSS (not the last one in the component instance's final class list) wins.
Tonight, I was thinking about the fairly new
:where()
selector. Awhere()
selector always has a selectivity score of 0 regardless of what is inside the parenthesis, meaning a mere class selector will override it. Support is mixed but it's getting close to critical mass.So what if we were to use this to create a variant of each style (say, with a prefix of
def:
ord:
), specifically meant for component authors, to define a "baseline" or "default" style?When authoring components, we could then use these prefixed classes for anything we want the component user to be able to override:
As a component user, I could then just use the normal Tailwind classes to override the defaults, meaning this now works as expected:
Here's a Fiddle with a more complete example:
https://jsfiddle.net/richardtallent/qLp4mby6/
This is a bit of a hack, but still feels like a contender among other solutions I've seen so far, such as:
@apply
for some TW UX benefit) to define the default style, then ensure the build process loads that CSS before Tailwind. Clunky at best.bg
prop with a default ofbg-gray-100
) and string those props together to create the class list. Messy, creates a ton of unnecessary JS, and doesn't handle partial overrides well (e.g., what if the component has a prop forborder
but you only want to overrideborder-style
?).Seems like this solution would be fairly compact, too (only need new selectors, not a copy of each rule), should purge just as well as anything else.
This would also allow component users to use semantic or other custom classes to override styles without having to worry about whether those classes will be loaded before or after Tailwind.
Thoughts?
Would this wreak havoc on interactions with other variants or pseudo-classes?
Any other fatal flaws I'm not thinking of?
Beta Was this translation helpful? Give feedback.
All reactions