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/
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With