0

I have 2 element Buttons and I want to change the color of one when I click another, and vice versa. I tried It, but don't work. Can anyone help Me? HTML:

<button id="t1">Test 1</button>
<button id="t2">Test 2</button>

CSS:

#t1:active + #t2
{
    color: red;
}
#t2:active + #t1
{
    color: red;
}
Wex
  • 15,539
  • 10
  • 64
  • 107

2 Answers2

2

There is no vice versa, as sibling combinators only work in one direction (from an earlier sibling to a later sibling). In other words, using CSS, you can only change #t2 when #t1 is clicked, but not #t1 when #t2 is clicked. Also, > is the child combinator, not a sibling combinator.

If you need the same behavior to work both ways, you have to use a JavaScript mousedown event instead of the :active selector.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Thank You, BoltClock. I will use Javascript –  Sep 13 '12 at 16:42
  • @user1628488 I hate to disagree with you, BoltClock, but this achievable without JavaScript: [little link](http://jsfiddle.net/glee/hk7jv). – Chris Sep 13 '12 at 16:50
  • 1
    @Abody97: Well, yeah, of course it works if you apply `:active` to the parent and then activate within the parent (that isn't `#t1`). I'm saying it's not possible to have the style take effect only when the second button is activated. – BoltClock Sep 13 '12 at 16:53
  • @BoltClock Yeah, sorry :) Although you can get something pretty close if you wrap them in a `div` and only act when that `div` is active: [little link](http://jsfiddle.net/glee/hk7jv). But yeah, you're right, it's conceptually impossible to do without any 'hacks'. – Chris Sep 13 '12 at 16:56
  • @user1628488 Another hack-y solution, which uses a duplicate of the first button: [little link](http://jsfiddle.net/glee/97QXF/). – Chris Sep 13 '12 at 17:09
  • 1
    @Abody97: Now *that* is clever ;) – BoltClock Sep 13 '12 at 17:11
  • @BoltClock I've merged those two methods into an answer and posted it. Hope you don't mind :) – Chris Sep 13 '12 at 17:14
2

There are a couple of ways I can think of to achieve this using CSS only, although they aren't completely "sincere".

The first method relies on creating a "fake" clone of the first button, and showing it when the second button is :active, demo: little link.

The second method relies on the fact that when one of your buttons is :active, then parent elements behind it are :active as well. Here's a demo of this solution: little link.

Chris
  • 26,544
  • 5
  • 58
  • 71