Style sibling of parent on hover of child

Viewed 178
<div class="main">
 <div class="parent">
  <div class="content-1"> A </div>
 </div>
 <div class="content-2"> B </div>
</div>

On hover of content-1, I want to style content-2

2 Answers

Well, I have found a solution for this, which I never used which is a ">" sign. I used Main for doing this, I used content-1 but it doesn't work for me, simce to me it act like then first-child and last-child or something like that. here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stack13</title>

    <style>
        
        .main:hover > .content-2{
            background-color: red !important;
            color: blue !important;
        }


    </style>



</head>
<body>

<div class="main">
    <div class="parent">
        <div class="content-1"> A </div>
    </div>
    <div class="content-2"> B </div>
</div>


</body>
</html>

.main{
  border: 1px black solid;
}

.content-1{
  border: 1px blue solid;
}

.main:hover > .content-2{
    background-color: red !important;
    color: white !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stack13</title>
</head>
<body>

<div class="main">
    <div class="parent">
        <div class="content-1"> A </div>
    </div>
    <div class="content-2"> B </div>    
</div>


</body>
</html>

It's currently impossible in CSS to style an element further UP the tree.

Hovever if you change your markup you can style the adjacent (next) sibling with the adjacent child selector + see below example

The code you have provided seems to contradict the title, as the title suggests styling a sibling where the code shows that the two are not siblings of the same parent.

.content-1:hover + .content-2 {
  background-color: yellow;
}
<div class="main">
  <div class="parent">
    <div class="content-1"> A </div>
    <div class="content-2"> B </div>
  </div>
</div>

Related