css :hover only affect top div of nest

Viewed 24307

Hi: got some html like:

<div class="class" >
    <div class="class" >
    </div>
</div>

And some css like:

div.class:hover
{
    border-width:2px;
    border-style:inset;
    border-color:red;
}

When I hover over the inner div, both divs get the red border. Is it possible to stop the propagation and get the red border on the inner div using css?

Thanks.

EDIT : starting with the answer pointed to by borrible I ended up with:

    $("div.class").mouseover(
        function(e) {
            e.stopPropagation();
            $(this).css("border-color", "red");
        }).mouseout(
        function() {
            $(this).css("border-color", "transparent");
        });

Shame it's not css but does the job. Thanks everyone, didn't get what I wanted but learned lots of new stuff. Ain't stack overflow great :)

5 Answers

I got the desired result by reworking a bit the html and using only css.

The HTML:

<div class="wrapper" > 
  <div class="parent"></div>
  <div class="child"></div>
</div>

And the CSS:

.wrapper {
  height: 500px;
  width: 500px;
  background-color: lightblue;
  position: relative;
}

.parent {
  height: 250px;
  width: 250px;
  background-color: lightgreen;
  top: 3em;
  left: 3em;
  position: absolute;
}

.parent:hover {
  border: 3px red solid;
}

.child {
  height: 50px;
  width: 50px;
  background-color: lightgrey;
  top: 5em;
  left: 5em;
  position: absolute;
}

.child:hover {
  border: 3px red solid;
}

https://jsfiddle.net/rafaelrozon/pynngjpk/

Basically instead of nesting the divs they can be siblings and then you can use css to make them look nested.

I hope it helps others.

You can add or remove a CSS class to the parent, when the child is hovered or not. So, you can listen to the child's onmouseenter and onmouseleave, in order to set a state in your parent component. Then, depending on the state, you can add the "child-hovered" class to the parent.

At the parent's CSS, you can check if it's hovered and doesn't have the class "child-hovered":

.parent-div:not(.child-hovered):hover {
  background-color: gray;
}
Related