HTML / CSS悬停一个对象以进行另一个更改其属性[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

大家好,感谢大家看看我的问题:我在这里:

#div1 {
  background: red;
  width: 200px;
  height: 200px;
}

#div2 {
  background: blue;
  width: 200px;
  height: 200px;
}
<div id="div1"></div>
<div id="div2"></div>

现在我想通过悬停div1将div2的背景变成绿色,我如何只用css做到这一点?

更新:我有一个相同的问题,但另一个故事:

--HTML--

<div id="div1"></div>

<div id="wrapper">
<div id="div2"></div>
</div>

--HTML--

--CSS--

#div1 {
      background: red;
      width: 200px;
      height: 200px;
    }

    #div2 {
      background: blue;
      width: 200px;
      height: 200px;
    }

    #wrapper{
      width:500px;
      height:500px;
    }

--CSS--

图:

#div1:hover + #wrapper #div2{
background:green;}

出于某种原因idk为什么#div1:hover + #div2不起作用

html css
2个回答
3
投票

您可以使用+ css选择器来执行此操作,该选择器直接在当前元素之后选择元素

div {
  height: 50px;
  width: 50px;
  border: 1px solid black;
}

#div1:hover+#div2 {
  background-color: green;
}
<div id="div1"></div>
<div id="div2"></div>

0
投票

干得好。尽管您保持HTML结构不变是很重要的。

#div1 {
  background: red;
  width: 200px;
  height: 200px;
}

#div2 {
  background: blue;
  width: 200px;
  height: 200px;
}

#div1:hover+#div2 {
  background: green;
}
<div id="div1"></div>
<div id="div2"></div>
© www.soinside.com 2019 - 2024. All rights reserved.