friedemann_bach friedemann_bach - 6 months ago 20
Javascript Question

Highlight another elements on hover with CSS

I have a HTML which looks like this:

<p>
<a id="foo" href="#bar">FOO</a><br/>
<a id="bar" href="#foo">BAR</a><br/>
</p>


Now I want to highlight "BAR" when "FOO" is hovered, and vice versa. Is there a way to accomplish this in CSS3, or do I need jQuery?

I have tried this:

a#foo:hover ~ a[href="#foo"] {
color:red;
background-color:blue;
}
a#bar:hover ~ a[href="#bar"] {
color:red;
background-color:blue;
}


But the ~ operator only works forward, so it will work fine for the first link, but not for the second one.

See also here: http://jsfiddle.net/pw4q60Lk/

Answer

In general, there's no previous sibling selector in CSS, this is to enable it to be applied on a single traversal of the document. But in your specific case you could take the following approach:

p:hover a:not(:hover) {
    color: red;
    background-color: blue;
}

http://jsfiddle.net/pw4q60Lk/2/

...although this does rely on the siblings completely filling the parent, as any hover over the parent alone will highlight both children.

Alternatively a (jQuery) script based approach would be:

$('a').hover(
    function() { $(this).siblings().addClass('highlight') },
    function() { $(this).siblings().removeClass('highlight') }
);

http://jsfiddle.net/pw4q60Lk/12/

Comments