简体   繁体   English

悬停在父元素上时子元素背景变化

[英]child element background change when hovering over parent

Objective 目的

I want the background color of my <p> (with the class of thumb-caption ) to change when I hover over the parent container. 当我将鼠标悬停在父容器上时,我想更改<p>的背景颜色(带有thumb-caption类)。

Background 背景

I have this demo on codepen that has a hover state on the parent and on the <p> but the <p> only changes color when you hover in it directly. 在codepen上有这个演示,它在父级和<p>上都具有悬停状态,但是<p>仅当您直接将其悬停在其上时才会更改颜色。

在此处输入图片说明

HTML HTML

<div class="system-thumb">
  <a href="https://www.google.com/search?btnG=1&pws=0&q=why+is+juan+so+awesome&gws_rd=ssl" target="_blank">                            
    <p><img src="http://placehold.it/360x180"><p>
    <h2>Product</h2>                            
    <p class="thumb-caption">You should totally buy this product, yay!</p>
  </a>
</div>

CSS CSS

.system-thumb {
  margin: 0 auto;
  max-width: 360px;
}
.system-thumb:hover {
  outline: 1px dotted #00aba7;
}
.system-thumb .thumb-caption {
  margin: 0;
  padding: 10px 5px;
}
.system-thumb .thumb-caption:hover {
  background-color: #00aba7;
  color: #fff;
}
.system-thumb p img {
  max-width: 100%;
}

Simple, apply the :hover psuedo-class to the parent element: 简单地,将:hover psuedo-class应用于父元素:

.system-thumb:hover p {
    background-color: #00aba7;
}

Before: 之前:

.system-thumb .thumb-caption:hover {
  background-color: #00aba7;
  color: #fff;
}

After: 后:

.system-thumb:hover .thumb-caption {
  background-color: #00aba7;
  color: #fff;
}

You need to assign who's going to have the event. 您需要指定谁去参加活动。 In this case, <p> will be affected only if its parent is hovered. 在这种情况下, <p>仅在其父对象悬停时才会受到影响。 So, you need to move the :hover element to the parent selector. 因此,您需要将:hover元素移动到父选择器。

Select the child ( .thumb-caption ) when it's hovered ( .system-thumb:hover ) .thumb-caption选择子项( .thumb-caption )(. .thumb-caption .system-thumb:hover

.system-thumb:hover .thumb-caption {
    /* Your css codes*/
}

That's simple. 很简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM