Home > OS >  Force TailwindCSS cherry picking of classes to pick up certain classes
Force TailwindCSS cherry picking of classes to pick up certain classes

Time:06-14

I'm currently using TailwindCSS in my Vue (with Vite) project and I want to use a dynamic width class depending on the size of a certain array.

const array = [1, 2, 3];
const width = computed(() => `w-1/${array.length}`);
<div :>Content</div>

The problem I'm facing is that when I use a dynamic width (w-1/4 for example) that is generated by a computed value it does not work. The only way I was able to get this working is by adding an element somewhere in my component that has all the possible classes I might use but this doesn't entirely feel correct.

<div >Content</div>

I've searched online and looked through the documentation but was unable to find someone else having my issue. I'm wondering if it's possible to somehow config TailwindCSS to always include the width classes (w-1/1, w-1/2, w-1/3, w-1/4, etc...) in the cherry picking process.

Thanks!

CodePudding user response:

Yes, it is possible with what is called "Safelisting classes" that is documented here: https://tailwindcss.com/docs/content-configuration#safelisting-classes

So you can add the classes to your config like this:

  safelist: [
    'w-1/2',
    'w-1/3',
    'w-1/4',
    ...
  ]

Note for w-1/1, it does not exist by default. You could add it to the config if needed, but otherwise w-1/1 would be ignored and if it is a block element it should default to 100% anyway.

module.exports = {
  theme: {
    extend: {
      width: {
        '1/1': '100%'
      }
    },
  },
}
  • Related