I need to implement design colour tokens in Tailwind.
The tokens are named semantically, with some examples being:
Text/Main/BodyPrimary
Surface/Background/Secondary
Border/Button/PrimaryOutline
I have added these tokens to Tailwind using the extend.colors
object in the tailwind.config.js
file, with the token paths above being implemented as follows:
extend: {
colors: {
text: {
main: {
bodyPrimary: #ffffff,
},
},
},
}
However, the tokens I have lead to clunky implementations in practice due to Tailwind requiring colours to be pre-fixed with the property that they are being applied to.
For example, the token above would have to be applied as follows:
<p className="text-text-main-bodyPrimary">
Hello
</p>
Is there a way to add tokens of this format to Tailwind that would bypass the duplication of the property they are being applied to (e.g. text-text...
, border-border...
)? Or, will I need to re-write the tokens without using words such as text, bg, border etc?
Classes for color
(text-<color>
), border-color
(border-<color>
), etc. have their own object key "group" as well as inheriting values from colors
. This means you could map your token prefixes to them, like:
Token Namespace | Tailwind Configuration Key | Class name prefix |
---|---|---|
Text |
textColor |
text |
Surface |
backgroundColor |
bg |
Border |
borderColor |
border |
tailwind.config = {
theme: {
extend: {
backgroundColor: {
background: {
// Surface/Background/Secondary
secondary: 'darkblue',
},
},
borderColor: {
button: {
// Border/Button/PrimaryOutline
primaryOutline: 'lime',
},
},
textColor: {
main: {
// Text/Main/BodyPrimary
bodyPrimary: 'lightpink',
},
},
},
},
};
<script src="https://cdn.tailwindcss.com/3.4.5"></script>
<div class="bg-background-secondary border border-button-primaryOutline text-main-bodyPrimary">
Foo
</div>