我有两个嵌套的
<div>
的
<div class="parent">
<div class="child"></div>
</div>
当我将鼠标悬停在
background
上时,我想将 .parent
更改为 .parent
。
当我将鼠标悬停在
background
上时,我希望 .child
再次恢复正常。
例如,当我将鼠标悬停在内部区域上时,我希望外部区域返回到其原始(灰色)状态:
.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>
我想保留这个
<div>
结构,并且我不需要 JavaScript 解决方案(我知道 JavaScript 解决方案,但我想保留它纯 CSS)。
这不是“将鼠标悬停在子对象上时如何设置父对象的样式”的重复。当鼠标悬停在孩子上方时,我不想设置父母的样式。
基本上你不能:如何在悬停子元素时设置父元素的样式?
但是一个技巧是使用同级元素: 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>
你可以欺骗一些东西;)
基本上,对子 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>