2016-12-05 240 views
2

是否可以將鼠標懸停在嵌套的子元素上而不觸發父元素上的懸停?如何將鼠標懸停在子元素上而不將鼠標懸停在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>

+0

因此,您需要在將鼠標懸停在子項上時修改父元素。目前無法在CSS中選擇父元素。看看這個問題的更多信息:http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Beno

回答

3

是否可以嵌套子元素懸停在無父元素觸發懸停?

不需要。因爲這兩個元素都需要懸停,所以如果沒有將父項懸停,則無法懸停該子項。

但是,如果嵌套不是必需的,則可以使.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>

1

基本上沒有。在遙遠的未來,你也許能夠使用像

:hover:not(:has(> :hover)) > .close { 
    display: inline-block; 
} 

(見Is there a CSS parent selector?

但目前則需要一些技巧,如@ Michael_B的答案。

或者,考慮使用JavaScript。

相關問題