On Tailwind CSS arbitrary values
- Published on
- /3 mins read/---
I have been using Tailwind CSS since 2018 and I super love the framework. It's so flexible, powerful, and brings so much joy writing CSS.
Here are some of my favorite tips when using Tailwind CSS Arbitrary Values to write custom styles for your components. Some of them are covered in the official documentation, some I couldn't find (maybe they are their hidden gems ), and some are just my own personal tricks.
NOTE
All the examples below are in React since I guess Tailwind is mostly used with a frontend framework.
Arbitrary values
Arbitrary values are values that are not predefined in the Tailwind CSS configuration. We use the square brackets annotation []
to generate a class on the fly with any value:
This will output the following CSS:
Referencing design tokens
We can use the theme()
function to reference design tokens in tailwind.config.js
:
Output CSS:
With CSS variables
We can also use CSS variables to generate arbitrary values:
You can get rid of the var(...)
wrapper, just provide the variable name is enough:
This will output the following CSS:
But for variables with fallback values to another variable, we still need to use the var(...)
wrapper:
Output CSS:
Injecting CSS variables
CSS variables can be injected into the DOM with inline styles like this:
But with arbitrary values, we can do this:
Which will output the same CSS variables declaration as above.
Out of the box utilities
For properties that are not supported by default in Tailwind CSS, we can also use the square bracket notation to write completely arbitrary CSS:
Handling whitespaces
We must remove whitespaces from the arbitrary classes to make them work or use the underscore notation _
for better readability:
Resolving namespace collisions
Many CSS properties share the same namespace in Tailwind CSS, for example bg-red-500
and bg-cover
, or text-gray-900
and text-2xl
.
To avoid collisions when using arbitrary values, we can prefix a CSS data types (color:
, length:
, etc.) to the property value:
This is super useful when using with variables, for example:
will output CSS for background color:
And adding a length:
prefix will output the css for background-size
:
Output:
That's some of my favorite notes when using Tailwind CSS Arbitrary Values. Do you have any other tips? Please let me know in the comment section
Happy styling (with Tailwind CSS)