-1

I have a big problem with coding on css

HTML

<div id='wrapper'>
     <div id='first'></div>
     ...
</div>
...
<div id='second'></div>

CSS

<style>
#first:hover ~ #second
{
     background:#000;
}
</style>

But it doesn't work. I need to change background of div[id=second] when the div[id=first] is hovered.

Dan
  • 8,983
  • 5
  • 37
  • 71
piv199
  • 1
  • 4
    You cannot do it with CSS only, once you pop in an element you cannot pop out and select another, use JS or you need to alter your markup – Mr. Alien Jul 31 '14 at 19:06
  • You can't do that. Try doing it with js. Here is an example: http://jsfiddle.net/82Nv7/ – Pablo Matias Gomez Jul 31 '14 at 19:11
  • You'd have to change your mark-up so that the #first and #second divs are siblings. CSS doesn't have parent selectors or closures. – TylerH Jul 31 '14 at 19:14

1 Answers1

2

Tilde ~ is the sibling selector, but #second is not the sibling of #first in your HTML. You need to place #second inside the wrapper for the ~ to work.

<style>
#first:hover ~ #second
{
     background:#000;
}
</style>

<div id='wrapper'>
    <!-- Now they share the same parent, so they are siblings -->
    <div id='first'>Hover over first</div>
    <div id='second'>To black out second</div>
</div>

If #second needs to be outside of #wrapper you must use Javascript to change the style of #second when the mouse is over #first. Plain CSS does not allow you to select "cousins".

<script>
    var third = document.getElementById('third'),
        fourth = document.getElementById('fourth');

    third.addEventListener('mouseover', function () {
        fourth.className = "blackout"
    });
    third.addEventListener('mouseout', function () {
        fourth.className = "";
    });
</script>

<style>
.blackout {
    background:#000;
}
</style>

<div id='wrapper2'>
    <div id='third'>Hover over third</div>
</div>
<div id='fourth'>To black out fourth</div>

Check out the live demo in a jsFiddle

cvializ
  • 576
  • 2
  • 11
  • thnx, i realy know all the ways, but i was surprised enough when i realised that i couldn't get the parent of any in css, waiting for css4. – piv199 Jul 31 '14 at 21:39