Vincent
Vincent

Reputation: 147

how to create a tailwind responsive class using a plugin

how can I reproduce the following scss using a plugin?

.large-title {
    font-family: $font-family-2;
    @apply leading-none; 
    color: $large-title-color;
    @apply uppercase;

    @apply text-xl;

    // I don't know how to add these in the plugin
    @apply sm:text-2xl;
    @apply md:text-3xl;
    @apply lg:text-4xl;
    @apply xl:text-5xl;
} 

in my config file, I currently have:

module.exports = {
[...]
  plugins: [
    require('@tailwindcss/forms'),
    plugin(function({ addBase, config }) {
      addBase({
        '.large-title': { 
          fontFamily: [config('theme.fontFamily.family-2')],
          fontSize: config('theme.fontSize.xl'),
          lineHeight: config('theme.lineHeight.none'),
          color: config('theme.colors.primary.900'),
          textTransform: 'uppercase',
        },
      })
    })
  ],
}

The only thing missing is I can't find out how to add the responsive size changes from the class in the plugin.

Upvotes: 0

Views: 2213

Answers (1)

Matt
Matt

Reputation: 940

One way to add @media queries to a class in Tailwind's CSS-in-JS syntax is nesting:

addBase({
  '.large-title': { 
    '@media (min-width: 500px)': {
      fontSize: theme('fontSize.xl'),
    }
  },
})

Additionally, user's breakpoints can be accessed using the theme() function:

const sm = theme('screens.sm', {})

Combining these two snippets you could:

const sm = theme('screens.sm', {})

addBase({
  '.large-title': { 
    `@media (min-width: ${sm})`: {
      fontSize: theme('fontSize.xl'),
    }
  },
})

One caveat to be aware of in case you're building this plugin for public use is that a user may entirely change their theme.screens config. If a user removes the theme.screens.sm key from their configurations, for example, the snippet above would no longer work.

Upvotes: 4

Related Questions