Tailwindcss how to use custom classes with responsive variants

Viewed 957

I'm in the process of picking the tech stack for the next mid size front end development in my company.

I picked (for now): Angular, Tailwindcss, PrimeNg, and PrimeIcons.

Now I'm becoming confortable with, or refreshing my knowledge with those technologies. Everything is gooing smoothly except one thing, I'm unable to get right with tailwind. PrimeNg has classes for its components like p-inputtext-sm or p-inputtext-lg I would like to set those clases based on responsive variants of tailwind.

Something like:

<input pInputText type="text" id="username" formControlName="username" class="w-full p-inputtext-sm lg:p-inputtext-lg">

Is it possible?

2 Answers

As Maik Lowrey said that is what components for. But you may create as many components as you wish

@layer components {
  .component-lg {
    @apply bg-red-500 text-3xl; 
  }

  .component-sm {
    @apply bg-green-500 text-sm;
  }
}

Every class under components layer may be used with responsive variants (even container - you may try it like lg:container)

<div class="text-white p-4 component-sm sm:component-lg">
  Hello World
</div>

Or you may create a plugin with CSS-in-JS syntax

// tailwind.config.js

const plugin = require('tailwindcss/plugin')

module.exports = {
  theme: {
    extend: {
      // ...
    },
  },
  plugins: [
    plugin(function ({ addComponents, theme }) {
      addComponents({
        '.component-plugin': {
          backgroundColor: theme('colors.amber.500'),
          fontSize: theme('fontSize.6xl'),
        },
      })
    }),
  ],
}

Both ways do same thing basically but with plugin you may create package and install it every time you need

<div class="text-white p-4 component-sm sm:component-lg md:component-plugin">
  Hello World
</div>

DEMO

You have to assign a new layer to component. In this component you can define your class and add tailwind classes. You can you the tailwind screen directives to make your custom class responsible.

Add to your css file where you input the tailwind css classes this:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .p-inputtext {
      @apply lg:bg-red-500 md:bg-green-500 sm:bg-blue-500 text-2xl lg:text-4xl;
  }
}
Related