Skip to content
Advertisement

Tailwind custom pseudo element

I’m trying to create a single js file for a component that is used with several styles in my project. On one page I have several buttons for some features, with a default background color set in the html file (for exemple bg-gray-500). For buttons where the feature is activated I change the background color, currently with js, but therefore the bg color for the “activated feature” (for exemple bg-blue-500) is defined in the js and this is what I would like to move to the html file. So, instead of having <button type="button" class="bg-gray-500"></button> and having the js removing the class bg-gray-500 and adding the class bg-blue-500, I wonder if this is possible to have something like <button type="button" class="bg-gray-500 selected:bg-blue-500"></button> where the js would only have to add or remove the class selected to switch between the one and the other color, instead specifing the color itself. Thank you

Advertisement

Answer

You may write simple plugin for custom variants

// tailwing.config.js

const plugin = require('tailwindcss/plugin')

module.exports = {
  theme: {
    extend: {},
  },
  plugins: [
    plugin(function({ addVariant }) {
      addVariant('selected', '&.selected');
      addVariant('parent-selected', '.selected &');
    })
  ],
}

HTML

<div>
  <button class="bg-blue-500 selected:bg-red-500 selected">
    Button
  </button>
</div>

<div class="selected">
  <button class="bg-blue-500 parent-selected:bg-yellow-500">
    Button
  </button>
</div>

The magic here is addVariant() function where the first parameter is variant name (could be any but must be unique among all variants – in HTML use it like selected:), second – CSS selector (so &.selected means element with class .selected) or callback function which should return string as CSS selector

In a demo I created two cases just for example – toggle class on element itself or parent element

DEMO – toggle selected class to see effect

Advertisement