Search code examples
tailwind-csscss-purge

Safelist all margin values with screen variants in Tailwind


I need to safelist all margin values with the respective responsive sizes.

Example:

  • 'mb-10'
  • 'md:mb-10'
  • 'xl:mb-10'

and so on.

Here is what I have right now in my tailwind.config.js but it doesn't seem to work for the responseive variants:

safelist: [
    {
      pattern: /\-?m(\w?)-/,
    },
],

Is there an easy way to achieve this with regex patterns or do I need any other specific configuration? I would of course like to avoid listing them all manually.


Solution

  • So I would like to preface this by saying that this behavior is not recommended if this is meant for a production site. Tailwind docs explicitly state safelisting is a last ditch effort. The file produced by this safelisting alone would be upwards of 80kb.

    That said, the part you're missing for responsive variants is the variants option as stated in the docs. But your regex pattern would also be grabbing more than just margin utilities.

    In order to prevent the inclusion of other classes that contain m- (bottom- and scroll-m-) you can add them in a non-capturing group before looking for the margin string.

    module.exports = {
      content: [],
      safelist: [
        {
          pattern: /^(?!(?:scroll|bottom)$)m\w?-/,
          variants: ['sm', 'md', 'lg', 'xl', '2xl'],
        },
      ],
    }