February 1, 2012

how can I use the CSS selector to solve this

Question by Mohammad Ereiqat

I have a problem with this code

<ul style="position: absolute; z-index: 999999999;">
    <li><a href="#" id="home_link">Home</a></li>
    <li><a href="#" id="hits_link">music</a></li>
    <li><a href="#" id="cinema_link">cinema</a></li>
    <li><a href="#" id="shows_link">shows</a></li>
    <li><a href="#" id="timeout_link">timeout</a></li>
    <li><a href="#" id="win_link">win</a></li>
  </ul>
<div id="logo"></div>

I need to change the background position of the div#logo when hover on any “a”

tried this CSS selector with no luck

ul li a#hits_link:hover + div#logo{background-position:-198px 0px;}

Please Advice

Answer by Andreas Carlbom

You can’t. There’s no selector that produces the behavior you want in CSS. Every CSS selector can only be used to affect an element and its descendants, not its siblings or any other totally unrelated element.

You’ll have to use jQuery/JavaScript for this.

Example:

$("ul li a").hover(function() {
    // When hovering, change the background-position of the #logo-element
    $("#logo").css("background-position", "-198px 0px");
},function() { 
    // When mouse moves away, revert the background-position
    $("#logo").css("background-position", "0px 0px");
});

I made you a fiddle. Treat it with care: http://jsfiddle.net/kMfWk/

Answer by Starx

You simply cannot do that, because #logo is not an adjacent sibling to #hits_link.

I have created a fiddle here to demonstrate what do you mean by adjacent sibling.

#logo is not related to #hits_link in any way, so AFAIK you will need the help of a js snippet to do something like that.

Using JQuery.. you can do something similar to this

$("#hits_link").hover(function() {
    $("#logo").css("background-position", "-198px 0px");
},function() { 
    $("#logo").css("background-position", "0px 0px");
});

Here is a demo to that as well.

Update:
On that case, the second function is reverting the background position to 0 0.

use only this, if you want it to stay like that

$("#hits_link").hover(function() {
    $("#logo").css("background-position", "-198px 0px");
});

Check demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!