当鼠标悬停在子元素上时,应该取消父元素的悬停效果。

49
我有两个嵌套的
元素。
<div class="parent">
    <div class="child"></div>
</div>

我想在鼠标悬停在.parent上时更改background

当我悬停在.child上时,我希望background恢复正常。

例如,当我悬停在内部区域时,我希望外部区域返回到其原始(灰色)状态:

.parent {
    width: 100px;
    height: 100px;
    padding: 50px;
    background: lightgray;
}

.parent:hover {
    background: lightblue;
}

.child {
    height: 100px;
    width: 100px;
    background: darkgray;
}

.child:hover {
    background: lightblue;
}
<div class="parent">
    <div class="child"></div>
</div>

我想保留这个
结构,并且不想用JavaScript解决方案(虽然我知道JavaScript解决方案,但我想保持纯CSS)。
这不是“如何在悬停子元素时样式化父元素”的重复问题。我想在悬停子元素时不要样式化父元素。

保持div并排,并使用定位使它们看起来像父子元素。 - Mr_Green
2
不要以为你可以通过CSS保持相同的HTML结构...悬停在子元素上总会触发父元素的悬停。你必须使用不同的结构或以另一种方式进行伪装。对于这个例子来说,这不是问题,但我认为对于更复杂的设置来说,这可能是一个问题。 - robooneus
我想保留这个<div>结构,不想用CSS进行奇怪的定位。说实话。 - EaterOfCode
这是Fiddle - Mr_Green
@Mr_Green 我无法将它们放在一起,这就是整个问题。 - EaterOfCode
显示剩余4条评论
2个回答

29

基本上你做不到:

如何在悬停子元素时为父元素设置样式?

但是有一个技巧是使用兄弟元素:http://jsfiddle.net/k3Zdt/8/

.parent {
  width: 100px;
  height: 100px;
  padding: 50px;
}

.child {
  height: 100px;
  width: 100px;
  background: #355E95;
  transition: background-color 1s;
  position: relative;
  top: -200px;
}

.child:hover {
  background: #000;
}

.sibling {
  position: relative;
  width: 100px;
  height: 100px;
  padding: 50px;
  top: -50px;
  left: -50px;
  background: #3D6AA2;
  transition: background-color 1s;    
}

.sibling:hover {
  background: #FFF;
}
<div class="parent">
    <div class="sibling"></div>
    <div class="child"></div>
</div>


3
谢谢 :) 这就是它了。这是我的最终结果 :) http://jsfiddle.net/k3Zdt/11/ - EaterOfCode
那是一个简单的例子,但是你有没有关于子 div 上随机大小内容的解决方案? - Matt Rose

14

你可以戏弄一些东西 ;)

基本上,对于子div使用一个与其相同大小的:before伪元素;

当你悬停在子div上时,将:before伪元素放大到覆盖父div区域;这将导致父div的hover效果消失,然后回到原始状态。还涉及到z-index的精确组合。

演示:http://jsfiddle.net/gFu8h/ 黑魔法(tm)

.parent {
    width: 100px;
    height: 100px;
    padding: 50px;
    transition: background-color 1s;
    background: #3D6AA2;    
    position: relative;
    z-index: 1;
}

.parent:hover{
    background: #FFF;    
}

.child {
    height: 100px;
    width: 100px;
    background: #355E95;
    transition: background-color 1s;
    position: relative;
}

.child:hover {    
    background: #000;
}

.child:before{
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;        
    z-index: -1;
    transition: background-color 1s;
}

.child:hover:before{
    top: -50px;
    bottom: -50px;
    left: -50px;
    right: -50px;     
    background: #3D6AA2;    
}
<div class="parent">
    <div class="child"></div>
</div>


2
+1 很酷.. 没有想过。 :) - Mr_Green
2
谢谢,这只是一个概念验证,如果需要的话,应该进行调整以使其更具动态性并更好地处理悬停退出(它仅在退出父级时恢复状态(因为它是透明的:before放大),但至少...纯CSS可以实现 :) - Andrea Ligios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接