Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!