使用以下 html,当我将鼠标悬停在子项上时,我会在父项上获得绿色背景.我怎样才能阻止这种情况发生?如果我悬停在子元素之外,我确实想要绿色背景.
With the following html, when I hover over child, I get a green background on parent. How can I stop that from happening? I do want the green background if I am hovering outside of the child element.
CSS3 很好.
.parent {
padding: 100px;
width: 400px;
height: 400px;
}
.parent:hover {
background-color: green;
}
.child {
padding: 100px;
width: 200px;
height: 200px;
}
.child:hover {
background-color: blue;
}
<div class="parent">
<div class="child">Child</div>
</div>
所以这真的很难看,但它确实有效(有点).我基本上是在创建父母的副本作为孩子的兄弟姐妹.parent-overwrite 默认隐藏,然后在 child 悬停时显示.Chrome 不喜欢它,除非您使用 + 选择器而不是 ~ 选择器.这不是很可扩展,但它可能会起作用.
So this is REALLY ugly, but it works (kind of). I'm basically creating a duplicate of parent as a sibling of child. parent-overwrite is hidden by default, then displayed on the hover of child. Chrome doesn't like it unless you use the + selector instead of the ~ selector. This isn't very scalable, but it may work.
正如其他人所说,javascript 可能是更好的解决方案.
As the other guys posted, javascript would likely be a better solution.
<style>
.parent { padding: 100px; width: 400px; height:400px; position: relative; z-index: 998; }
.parent:hover { background-color: green; }
.child { padding: 100px; width: 200px; height:200px; position: relative; z-index: 1000; }
.child:hover { background-color: blue; }
.parent-overwrite { padding: inherit; width: inherit; height: inherit; position: absolute; top: 0; left: 0; z-index: 999; background-color: #FFF; display: none; }
.child:hover ~ .parent-overwrite { display: block; }
</style>
<div class="parent">
<div class="child">Child</div>
<div class="parent-overwrite"></div>
</div>
这篇关于如何应用 child:hover 但不是 parent:hover的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!