Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Selecting unrelated element using element:hover pseudoclass

I have a button on my webpage. I want to use CSS pseudo-classes to make changes to a different part of the document when the cursor hovers over the button. This is what I've tried:

<div id="content">
    <p id="foo">blah blah blah</p>
    <p id="blah">blah blah blah</p>
</div>

<div id="navigation-panel">
    Hover over a button!
    <div class="buttons">
        <div id="button1">button1</div>
        <div id="button2">button2</div>   
        <div id="bar">bar</div>
    </div>
</div>

And the corresponding style sheet:

#bar:hover #foo {
    color: green;
}

But of course this doesn't work, because in CSS you can only use a selector of the format A B to select a B descendant of element A. With the new CSS3 spec, it's possible to select a sibling element of A using some new pseudo-classes.

But is there a way to select one (or more) elements B that are more like distant cousins to A?

I was thinking of a couple solutions. One: use Javascript. This doesn't sound too appealing to me because I'm hoping to make my page entirely functional without JS, in case there is somebody browsing my page who has JS disabled in their browser. Also I'm hoping to keep things simple. The second solution: put the foo div inside the bar div and then use position: absolute to move foo where I want it to end up. This is a messy solution, for reasons that should be obvious.

like image 476
jayhendren Avatar asked Oct 14 '25 03:10

jayhendren


2 Answers

Yeah, but not with CSS. Use JavaScript. Here's a jQuery example.

$('#bar').hover(
  function(e) {
    $foo = $('#foo');
    $foo.data('prevColor', $foo.css('color'));
    $foo.css('color', 'green');
  },
  function(e) {
    $foo = $('#foo');
    $foo.css('color', $foo.data('prevColor'));
  }
);
like image 136
scottheckel Avatar answered Oct 18 '25 02:10

scottheckel


You could put it inside the container and then absolutely position it outside of the container's DOM flow to give the same effect. It's not totally ideal but it's possible:

<div id="content">
    <p id="blah">blah blah blah</p>
</div>

<div id="navigation-panel">
    Hover over a button!
    <div class="buttons">
        <div id="button1">button1</div>
        <div id="button2">button2</div>   
        <div class="foo" id="bar">bar<p id="foo">blah blah blah</p></div>
    </div>
</div>

#content {
    height:80px;
}

#foo {
    position:absolute;
    top:40px;
}

#bar:hover #foo {
    color: green;
}

http://jsfiddle.net/Uyypc/

like image 34
AlienWebguy Avatar answered Oct 18 '25 03:10

AlienWebguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!