Sangram Jagtap Sangram Jagtap - 4 months ago 9
CSS Question

How to write conditional css?

If user hovers on div1, div2 should get highlighted.
How to write such conditional css?
HTML:

<body>
<div class='div1'></div>
<div class='div2'></div>
</body>

Answer

Here I used the sibling selector ~.

div {
  height: 30px;
}
.div1 {
  background: red;
}
.div2 {
  background: blue;
}
.div1:hover ~ .div2 {
  background: yellow;
}
<div class='div1'></div>
<div class='div2'></div>

If there would be more than 1 div2 and you only want the first immediate use the adjacent sibling selector +

div {
  height: 30px;
  margin-top: 5px;
}
.div1 {
  background: red;
}
.div2 {
  background: blue;
}
.div1:hover + .div2 {
  background: yellow;
}
<div class='div1'></div>
<div class='div2'></div>
<div class='div2'></div>

Comments