Mazdak
Mazdak

Reputation: 781

Nested Div hover question

I have 3 html div like this:

<div id="MainDiv">
  <div id="nesteddiv1"></div>
  <div id="nesteddiv2"></div>
</div>

I want when I hover on MainDiv or nestedDiv1 , I set color 1 for MainDiv and color 2 for nesteddiv2 , then when I hover on nesteddiv2 I change the backgroundcolor of nesteddiv2 and MainDiv.

I prefer to do it with CSS, I know the javascript way.

Thanks Mazdak

Upvotes: 1

Views: 2105

Answers (4)

kikito
kikito

Reputation: 52641

The only way of doing that with CSS only is using an extra div to cover maindiv when the hover happens. And it would not work on IE < v9, since it would need z-index

This would be the markup

<div id="MainDiv">
  <div id="nesteddiv1"></div>
  <div id="nesteddiv2">
    <div id="extradiv"><div>
  </div>
</div>

The CSS would be very tricky.

(disclaimer: this hasn't been tested - probably you would need more rules)

  • MainDiv would have to be position:relative or position:absolute, fixed width and height, and z-index = -1.
  • Nested divs 1 and 2 can NOT be position:relative or absolute, and z-index = 1
  • Extra div would have to be: position:absolute, top:0, left:0, and same witdth and height as MainDiv, display:hidden, and z-index = 0
  • #nexteddiv2:hover #extradiv would have display:block

z-index would make maindiv stay allways behind the others, while nested divs 1 and 2 always stay on top. extradiv would be between them, 'covering' maindiv, but only when nesteddiv2 is hovered.

A drawback of this method would be that extradiv would be visible until you stopped hovering it, not just nesteddiv2.

Upvotes: 0

Kyle
Kyle

Reputation: 67194

There is no way to select an element from another, it's just not possible.

But you can do this with jQuery like this:

$(function() {
    $("#div1").hover(function() {
        $("#show-hide").toggleClass('highlight');
    });
});

I have made an example for you here.

Upvotes: 0

Chinmayee G
Chinmayee G

Reputation: 8117

For given HTML you can do with following CSS

#MainDiv:hover{
    color:red;
}

#MainDiv div#nesteddiv1{
    color:gray;
}

#MainDiv div#nesteddiv1:hover{
    color:blue;
}

#MainDiv div#nesteddiv2{
    color:yellow;
}

#MainDiv div#nesteddiv2:hover{
    color:green;
}

Note: This will not work in IE as it supports hover only on a tag.

Upvotes: 0

Quentin
Quentin

Reputation: 943175

There is no way, in CSS, to target an element using a selector that includes one of its descendents. So while the first half is trivial to achieve, the second half is impossible.

Use JavaScript if it matters that much.

Upvotes: 2

Related Questions