如何让 css 悬停效果以不同方式影响子元素?

How to have css hover effect affect child elements differently?

我有一个矩形 div,里面有 2 个组件。图像元素和其下的 div 文本。我想对整个 div 做一个悬停效果,以不同的方式影响两个子组件。

例如,我希望图像具有不同的亮度,文本具有不同的背景颜色和文本颜色(但亮度不变)。

这是一个fiddle的骨架(一个主div包含2个子div),但是css不是我想要的。 https://jsfiddle.net/jhbf5c9n/

HTML:

<div class="main-container">
<!--  this div should have decrease in brightness -->
  <div class="effect1">
    <img src="http://placehold.it/200x100">
  </div>
<!-- this div should have constant 100% brightness, but background color and font color should change -->
  <div class="effect2">
    <p>This div should change background</p>  
    <p>And font color</p>
  </div>
</div>

CSS:

p{
  margin: 0;
}
div.main-container {
  height: 200px;
  width: 200px;
}
div.effect1 {
  width: 200px;
  height: 100px;
  background-color: blue;
}
div.effect2 {
  width: 200px;
  height: 100px;
  background-color: green;
}
div.main-container:hover {
  -webkit-filter: brightness(50%);
  background-color: blue;
  color: white;
}

主要目标是让单个悬停事件针对不同的子元素以不同的方式触发 css。谢谢!

在您的 fiddle 中,您可以使用以下代码来获得所需的结果:

div.main-container:hover .effect1 {
   -webkit-filter: brightness(10%);
}

同样,您也可以为其他 child 做。

如果你想在 div 上做一些悬停效果,这会改变它的 child 中的某些内容,那么你可以这样做

 .main-container:hover > .effect1 > img {
      -webkit-filter: brightness(50%);
 }

 .main-container:hover > .effect2 > p{
     background-color: blue;
     color: white;
 }

这将在单次悬停时更改效果 1 中的图像和效果 2 中的文本的亮度。希望这是你的答案