悬停的CSS颜色孩子

时间:2014-03-10 10:35:13

标签: css hover parent

我得到了这个:

<div id="father">
    <span class="child1"><span>
    <div class="child2"><div>
</div>

我需要在父亲身上改变child2的文字颜色:悬停,我能够做到这一点, 但是当我将鼠标悬停在child1上时,child2颜色松散且正常显示,我如何设置悬停在child1上,以免松散悬停效果?

我已经尝试过并且无效

.child1:hover .child2{ color: #eed847; }

感谢

4 个答案:

答案 0 :(得分:2)

.child1在您的示例中不是.child2的父级,这是您在选择器中使用空间所期望的。

.child1.child2中的任何一个悬停时,以下选择器应该有效。

#father:hover .child2 { ... }

Demo

答案 1 :(得分:0)

如果您不想更改第二个孩子的文字颜色,可以使用这样的解决方法:

#father:hover .child2 {color: #eed847;}
.child2:hover {color: #000!important;}

在此示例中,当您将鼠标悬停在child2上时,child2的文字将保持黑色。

答案 2 :(得分:0)

您可以在CSS Chris Coyier has written a fair bit about them here中使用兄弟选择器。

.child1:hover + .child2 { #some css };

答案 3 :(得分:0)

HTML的结束标记无效。我修改了你的HTML并为你需要的行为添加了css。

<强> HTML

<div id="father"> <span class="child1">child1</span>
    <div class="child2">child2</div>
</div>

<强> CSS

#father {
    width: 100px;
    height: 100px;
    background-color: cornflowerblue;
}
.child1 {
    background-color: green;
}
.child2, #father span.child1:hover + div.child2 {
    background-color: blue;
}
#father:hover .child2 {
    background-color: red;
}

<强> Working Fiddle