【问题标题】:How do I hover over a child element without hovering over the parent in CSS?如何将鼠标悬停在子元素上而不悬停在 CSS 中的父元素上?
【发布时间】:2017-04-19 09:59:51
【问题描述】:
是否可以将鼠标悬停在嵌套的子元素上而不触发父元素上的悬停?
在下面的示例中,您会看到当您将鼠标悬停在子对象上时,父悬停效果仍然处于活动状态。
我想对此进行更改,以便当您将鼠标悬停在子元素上时,父元素会返回其“未悬停”状态。
这可以通过 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>
【问题讨论】:
标签:
html
css
css-selectors
hover
【解决方案1】:
是否可以将鼠标悬停在嵌套的子元素上而不触发父元素上的悬停?
没有。由于这两个元素都需要悬停,因此您不能悬停子元素而不悬停父元素。
但是,如果嵌套不是必需的,您可以将 .child 元素设为兄弟元素。然后,使用绝对定位,将“子”置于“父”之上。
通过从文档流中删除“子”,“父”永远不会知道它的存在。因此,元素之间没有悬停关联。
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>
【解决方案2】:
基本上没有。在遥远的未来,您也许可以使用类似的东西
:hover:not(:has( > :hover)) > .close {
display: inline-block;
}
(见Is there a CSS parent selector?)
但目前你需要一些技巧,比如@Michael_B 的回答。
或者,考虑使用 JavaScript。