【问题标题】:How to have css hover effect affect child elements differently?如何让css悬停效果对子元素产生不同的影响?
【发布时间】:2016-04-15 07:22:51
【问题描述】:

我有一个包含 2 个组件的矩形 div。一个 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。谢谢!

【问题讨论】:

    标签: html css transition


    【解决方案1】:

    如果你想对 div 做一些悬停效果来改变它的子元素,那么你可以这样做

     .main-container:hover > .effect1 > img {
          -webkit-filter: brightness(50%);
     }
    
     .main-container:hover > .effect2 > p{
         background-color: blue;
         color: white;
     }
    

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2015-10-27
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        相关资源
        最近更新 更多