Html 在父悬停时更改子 div 的字体颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12628530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:03:49  来源:igfitidea点击:

Changing the child div's font colors on parent hover

htmlcss

提问by Arken

I have a question and I am not sure if it is possible, but I thought I would try asking.

我有一个问题,我不确定是否可行,但我想我会尝试提问。

Say I had three div's:

假设我有三个 div:

<div id="parent_div">

   <div id="child_div_1">Blue</div>

   <div id="child_div_2">Red</div>

</div>

If all text inside parent_div is set to black, how would I make the child_div_1and child_div_2change font-color to blue and red respectively, when the parent div is hovered over?

如果里面parent_div的所有文字设置为黑色,我怎么会做出child_div_1child_div_2改变字体颜色为蓝色,分别为红色,当父DIV悬停?

Sorry if this is a bit confusing, but is there a way to do this preferably with CSS only?

对不起,如果这有点令人困惑,但是有没有办法最好只使用 CSS 来做到这一点?

回答by Denys Séguret

#parent_div:hover #child_div_1 {
   color: blue;
}
#parent_div:hover #child_div_2 {
   color: red;
}

回答by David says reinstate Monica

Just target the relevant child elements based upon the :hoverstate of the parent:

只需根据:hover父元素的状态定位相关的子元素:

/* defaults */
#parent_div div {
    color: #000; /* or whatever... */
}

/* hover rules */

#parent_div:hover #child_div_1 {
    color: blue;
}
#parent_div:hover #child_div_2 {
    color: red;
}

JS Fiddle demo.

JS小提琴演示

回答by Guffa

Use the :hoverpseudo-class on the parent element:

:hover在父元素上使用伪类:

#parent_div { color: black; }

#parent_div:hover #child_div_1 { color: blue; }
#parent_div:hover #child_div_2 { color: red; }

Demo: http://jsfiddle.net/Guffa/M3WsW/

演示:http: //jsfiddle.net/Guffa/M3WsW/