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

时间:2016-01-11 03:36:37

标签: html css css3 transition

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

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

这是一个骨架的小提琴(一个包含2个子div的主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不同。谢谢!

2 个答案:

答案 0 :(得分:4)

如果你想在div上做一些悬停效果,这会改变孩子的某些东西,那么你可以这样做

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

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

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

答案 1 :(得分:1)

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

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

同样,你也可以为其他孩子做。

相关问题