2

Is it possible to hover over a nested child element without triggering a hover on the parent element?

In the example below you'll see that when you hover over the child, the parent hover effect is still also active.

I'd like to change this so that, when you hover over the child element, the parent returns to its "un-hovered" state.

Is this possible with CSS?

body {
  font-family: sans-serif;
}
div {
  padding: 1em;
  margin: 1em;
  border: 1px solid #ccc;
}
.close {
  display: none;
  float: right;
}
.parent:hover > .close {
  display: inline-block;
}
.child:hover > .close {
  display: inline-block;
}
<div class="parent">
  <a href="" class="close">Close parent</a>
  This is the parent
  <div class="child">
    <a href="" class="close">Close child</a>
    This is the child
  </div>
</div>
Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
Andrew
  • 3,246
  • 5
  • 33
  • 44
  • So you need to modify the parent element when you hover over the child. It is not currently possible to select a parent element in CSS. Check out this question for more info: http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Beno Dec 05 '16 at 04:17

2 Answers2

3

Is it possible to hover over a nested child element without triggering a hover on the parent element?

No. Since both elements call for hovering, you can't hover the child without also hovering the parent.

However, if nesting isn't essential, you can make the .child element a sibling instead. Then, using absolute positioning, place the "child" over the "parent".

By removing the "child" from the document flow, the "parent" never knows it exists. Hence, there is no hover association between elements.

body {
  font-family: sans-serif;
  position: relative;
}
.parent {
  height: 100px;
}
.child {
  position: absolute;
  width: 80%;
  left: 50%;
  top: 50px;
  transform: translateX(-50%);
}
div {
  padding: 1em;
  border: 1px solid #ccc;
}
.close {
  display: none;
  float: right;
}
.parent:hover > .close {
  display: inline-block;
}
.child:hover > .close {
  display: inline-block;
}
<div class="parent">
  <a href="" class="close">Close parent</a> This is the parent
</div>
<div class="child">
  <a href="" class="close">Close child</a> This is the child
</div>
Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
1

Basically, no. In a distant future you might be able to use something like

:hover:not(:has( > :hover)) > .close {
  display: inline-block;
}

(see Is there a CSS parent selector?)

But currently you will need some tricks like @Michael_B's answer.

Alternatively, consider using JavaScript.

Community
  • 1
  • 1
Oriol
  • 225,583
  • 46
  • 371
  • 457