Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight another elements on hover with CSS [duplicate]

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/

like image 869
friedemann_bach Avatar asked Apr 02 '26 20:04

friedemann_bach


2 Answers

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/

like image 62
stovroz Avatar answered Apr 04 '26 09:04

stovroz


As mentioned in this post, there is no previous sibling selector.

With the help of Jquery you can achieve it using hover() and mouseover() function.

HTML

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

Jquery

$("#bar").hover(function(){
    $('#foo').css({'color':'red','background-color':'blue' });
});
$("#bar").mouseout(function(){
    $('#foo').css({'color':'blue','background-color':'white' });
});

$("#foo").hover(function(){
    $('#bar').css({'color':'red','background-color':'blue' });
});
$("#foo").mouseout(function(){
    $('#bar').css({'color':'blue','background-color':'white' });
});

Fiddle is here

like image 36
sasi Avatar answered Apr 04 '26 09:04

sasi