I've been finishing off the build of my site over the last few weeks, and an issue cropped up recently that is obvious when you know about it, but did have me thinking for a short while 🤔.
Computed properties
I'm building my site with VueJS and Tailwind (plus Typescript ❤️ - more on that in a future post!) and I have a component that is rendered in a loop. I wanted to offset the position of the component incrementally based on the index of the loop. Simple stuff right?
To achieve this I created a computed class property which increased the left value based on the index.
const classes = computed(() => `relative md:left-${(blockIndex + 1) * 8}`)
This sounds fine on paper, but didn't render as expected - no left value was being applied. Then I remembered that Tailwind works by scanning all of your HTML, JavaScript components, and any other template files for class names, then generating all of the corresponding CSS for those styles. To be fair, it's written as exactly that in the docs 🤦♂️
In the instance above, Tailwind wasn't able to see the final class names i.e. left-8 or left-16 and so the generated CSS didn't contain those classes. This means you don't get the result you're looking for.
How can we fix this?
To fix this we need to make sure that the Tailwind compiler can read full class names in the file. To do this I implemented the below which now allows Tailwind to read the classes, and whilst having limitations, is simple and works for the context of what I'm building.
const marginClassMap: string[] = [ // ignore the Typescript `: string[]` if you're not using it
'md:left-8',
'md:left-16',
'md:left-24',
'md:left-32',
'md:left-40',
'md:left-48',
]
const classes = computed(() => `relative ${marginClassMap[blockIndex]}`)
You could also add position to the corePlugins array in your tailwind.config.js, but this way keeps the generated CSS lighter, and you've always got to have page speed in mind, even if just a small gain!
In summary
Always make sure that the Tailwind compiler can "make sense" of the classes in your files. In this instance it meant ensuring full class names were available in the source for Tailwind to see.
Also, make sure you remember what you've read in the documentation! 😅