简体   繁体   中英

tailwind css change color of button on focus

i have two buttons, blue and red.

i want to set when red button is clicked/focused blue button should also turn red.

how can i achieve it using tailwind css.

 <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/> <button class="focus:bg-red-700 bg-red-400 font-bold px-4 py-4 rounded-lg"> RED </button> <button class=" bg-blue-400 font-bold px-4 py-4 rounded-lg"> BLUE </button>

Tailwind don't has the css combinators . Guess, you have two way to achieve this.

  1. Create an extra css file and add this line
button.bg-red-400:focus ~ button.bg-blue-400 {
  background-color: rgba(185, 28, 28, 1);
}

 button.bg-red-400:focus~button.bg-blue-400 { background-color: rgba(185, 28, 28, 1); }
 <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" /> <button class="focus:bg-red-700 bg-red-400 font-bold px-4 py-4 rounded-lg">RED</button> <button class="bg-blue-400 font-bold px-4 py-4 rounded-lg">BLUE</button>

  1. You can create your own custom class with @Variants documentation , but not with a link from CDN.

Before using the CDN build, please note that many of the features that make Tailwind CSS great are not available without incorporating Tailwind into your build process. documentation

  1. Solution with javascript

 // Select all elements with `bg-blue-400` class const blueBox = document.querySelectorAll('.bg-blue-400'); const changeColor = ev => { // Define button in the DOM const button = ev.target.closest('button'); // Check, if the button was clicked if (button) { // Chenge color in the DIVs for (const box of blueBox) { box.classList.add('bg-red-400'); box.classList.remove('bg-blue-400'); } return; } // If clicked outside, the color will switch back for (const box of blueBox) { box.classList.add('bg-blue-400'); box.classList.remove('bg-red-400'); } }; document.addEventListener('click', changeColor);
 <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" /> <div> <button class="one bg-red-400 font-bold px-4 py-4 rounded-lg">RED</button> <div class="bg-blue-400 font-bold px-4 py-4 rounded-lg">BLUE</div> </div> <div class="two bg-blue-400 font-bold px-4 py-4 rounded-lg">APPLY COLOR HERE</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM