Change color of button using css or tailwind

Viewed 2982

i am trying to change color on buttons when main button is clicked, one color is changing why the other buttons color is not changing, is it because it's outside main <div> how can i achieve it, without removing any div.

code

button.one:focus~div.two {
  background-color: rgba(185, 28, 28, 1);
}
<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">MAIN BUTTON</button>

<div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">RED
</div>

</div>

<div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">MAKE THIS RED TOO</div>

1 Answers

Edit

In Chrome, the button was taking the click, and the parent div was not receiving the focus. I made a few adjustments to this and it is now working properly in Chrome.

  1. Ignore direct clicks to the button via pointer-events: none.
  2. To keep things somewhat accessible, I added:
    • aria-hidden="true" to the button, so that screen readers won't read it aloud to users.
    • aria-label="MAIN BUTTON" and role="button" to the parent div, so that screen readers can treat the div` like a button.
    • cursor: pointer to the parent div, so that it feels like a button (from a UX perspective).

The only pure CSS way to do this is to add tabindex="0" to the outer div, which lets us use its focus and general sibling combinator (~) to our advantage. I gave the div an inline inline-block display, so that the clickable region was the exact width of its child content.

div[tabindex="0"] {
  display: inline-block;
  outline: none;
  cursor: pointer;
  z-index: 1;
}

div:focus .two,
div:focus~.two {
  background-color: rgba(185, 28, 28, 1);
}

div[tabindex="0"] > button {
  pointer-events: none;
}
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />


<div tabindex="0" role="button" aria-label="MAIN BUTTON">

  <button aria-hidden="true" class="one bg-red-400 font-bold px-4 py-4 rounded-lg">MAIN BUTTON</button>

  <div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">RED
  </div>

</div>

<div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">MAKE THIS RED TOO</div>

Related