[英]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? 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. 但是,如果嵌套不是必需的,则可以使
.child
元素成为同级元素。 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? ) (请参阅是否有CSS父选择器? )
But currently you will need some tricks like @Michael_B's answer. 但目前您将需要一些技巧,例如@Michael_B的答案。
Alternatively, consider using JavaScript. 或者,考虑使用JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.