friedemann_bach friedemann_bach - 1 year ago 138
Javascript Question

Highlight another elements on hover with CSS

I have a HTML which looks like this:

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

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"] {
a#bar:hover ~ a[href="#bar"] {

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

See also here:

Answer Source

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;

...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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download