【问题标题】:How to change background of child element when parent element is hovered?悬停父元素时如何更改子元素的背景?
【发布时间】:2018-11-28 04:35:30
【问题描述】:

我有下一个 html 结构:

<div class="parent">
    <div class="child"></div>
</div>

还有css:

.parent {
    width: 100px;
    height: 100px;
}

.parent:hover {
    background-color: red;
}

.child {
    width: 50px;
    height: 50px;
}

当父 div 悬停时,如何更改子 div 的背景颜色?我可以使用 css 还是应该使用 JQuery?

【问题讨论】:

  • 我看到很多人已经回答了。但如果您想了解更多信息,请考虑阅读This Link

标签: css


【解决方案1】:

给你一个解决方案

.parent {
  background-color: green;
  width: 100px;
  height: 100px;
}

.parent:hover > .child{
  background-color: red;
}

.child {
  width: 50px;
  height: 50px;
}
<div class="parent">
    <div class="child"></div>
</div>

希望这会对你有所帮助。

【讨论】:

    【解决方案2】:

    你可以试试这个

    .parent:hover .child {
       background-color: red;
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      .parent:hover .child {
        background-color: blue;
      }
      

      .parent {
        width: 100px;
        height: 100px;
      }
      
      .parent:hover {
         background-color: red;
      }
      
      .parent:hover .child{
        background-color: blue;
      }
      
      .child {
        width: 50px;
        height: 50px;
      }
      <div class="parent"> PARENT
        <div class="child">CHILD</div>
      </div>

      【讨论】:

        【解决方案4】:

        如果我理解正确,你只需要改变

        .parent:hover {
            background-color: red;
        }
        

        .parent:hover .child {
            background-color: red;
        }
        

        【讨论】:

          【解决方案5】:

          为 .parent:hover .child 添加新规则

          查看以下示例:

          .parent {
              width: 100px;
              height: 100px;
              background-color:blue;
          }
          
          .parent:hover,
          .parent:hover .child  {
              background-color: red;
          }
          
          .child {
              width: 50px;
              height: 50px;
          }
          
          .child {
          background-color:yellow;
          }
          <div class="parent">
              <div class="child"></div>
          </div>

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-18
            • 2014-10-29
            • 2011-07-01
            • 2014-12-07
            • 2017-07-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多