简体   繁体   中英

How do I hover over a child element without hovering over the parent in CSS?

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> 

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM