s4nji
s4nji

Reputation: 455

Apply same effect to all elements with the same tabindex on focus of one of them

On my last one, I asked how to make unfocusable elements become focus-able in the means of css selector. The answer is to use tabindex.

Now I wanted that, when an element with the selector is focused (clicked), the other element selected by the selector also got the effect. It may sound strange, but I could do that a long time ago accidentally, but I forgot how.

Here is the jsfiddle example : http://jsfiddle.net/s4nji/xa8j4/

Upvotes: 4

Views: 3086

Answers (1)

Purag
Purag

Reputation: 17061

This selector does the trick:

li[tabindex='1']:focus ~ li[tabindex='1'], li[tabindex='1']:focus {
    background: black;
    color: white;
}

Here's an example.

It only selects both when you focus on the first one though.

This only works in CSS3 since we're using the general sibling selector.

When the first one is focused, it selects the second one with the same tabindex and adds the background. The second li[tabindex='1']:focus is to apply the background to the currently focused one too.

The general sibling selector can only select succeeding elements with the same parent. CSS can't travel up the DOM, unfortunately. For this reason, the only way to have it work backwards too would be to use Javascript.

Upvotes: 6

Related Questions