CSS鼠标悬停时更改盒子内元素的颜色

3

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>

    .box {
     height: 200px;
     width: 200px;
     border: 1px solid #eee;
    }
    
    .icon {
  position: absolute;
  width: 100px;
  height: 100px;
  left: 50px;
  top: 80px;
       fill: black;
    }
    
    .test-title {
     text-align: center;
     font-size: 22px;
    }
    
    .box:hover {
     
    }
     
</style>
</head>

<body>
 <div class="box">
  <p class="test-title">Undo Icon</p>
  <svg  viewBox="0 0 32 32" preserveAspectRatio="xMidYMin slice" class="icon">
   <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="test.svg#icon-undo"></use>
  </svg>
 </div>
</body>

</html>

上述代码产生以下输出

plain output

但是我希望在鼠标悬停在 .box 类上时获得以下输出

enter image description here

我可以通过 .test-title:hover { colour:red; } 改变字体的颜色,对于svg图像,我可以使用 .icon:hover { fill:red } 来着色,但是我希望在.box悬停时更改图像和文本的颜色。
1个回答

4

尝试使用子CSS选择器 (>) 来完成这个操作:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>

    .box {
     height: 200px;
     width: 200px;
     border: 1px solid #eee;
    }
    
    .icon {
  position: absolute;
  width: 100px;
  height: 100px;
  left: 50px;
  top: 80px;
       fill: black;
    }
    
    .test-title {
     text-align: center;
     font-size: 22px;
    }
    
    .box:hover, .box:hover > .icon {
     color: red;
      fill: red;
    }
     
</style>
</head>

<body>
 <div class="box">
  <p class="test-title">Undo Icon</p>
  <svg  viewBox="0 0 32 32" preserveAspectRatio="xMidYMin slice" class="icon">
   <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://139.59.35.115/test.svg#icon-undo"></use>
  </svg>
 </div>
</body>

</html>

注意: 请查看示例中的最后一个CSS规则,以了解其工作原理。

希望这能帮到你!


谢谢@HudsonTaylor,它按照我需要的方式工作了,但您忘记添加fill:red - Harish
糟糕,刚刚才注意到!抱歉。您能否将答案标记为正确的吗?我已经修复了错误 :) - Hudson Taylor
请让我等待5分钟。 - Harish
没问题。祝你的项目好运! - Hudson Taylor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接