343N 343N - 5 months ago 32
CSS Question

Hover over/click on div to affect another div?

I'm trying to affect 3 other div's when I hover over/click on one but it doesn't want to work.

#header2:hover {
background-color: rgba(10,50,10,0.9);
}
#header2:active {
background-color: rgba(0,0,0,0);
}
#header2:active ~ #header1{
background-color: rgba(0,0,0,0.8);
}
#header2:active ~ #header3{
background-color: rgba(50,10,10,0.8);
}
#header2:active ~ #header4{
background-color: rgba(10,10,50,0.8);
}


https://jsfiddle.net/ThinkingStiff/a3y52/
In this example I found whilist trying to find out the problem, it works fine, and I can't see any differences. The elements aren't children or parents of eachother either. (And I'd like to fix this without Javascript/Jquery if possible)

My HTML:

<div id="header1"><a data-scroll id="link1" href="#header1content"></a></div>
<div id="header2"><a data-scroll id="link2" href="#header2content"></a></div>
<div id="header3"><a data-scroll id="link3" href="#header3content"></a></div>
<div id="header4"><a data-scroll id="link4" href="#header4content"></a></div>

Answer

In order to make this work, #header2 should be the first element in your markup. You can use flex to make it work as shown below:

.headers {
  flex-direction: column;
  display: flex;
}
.headers div {
  background: #ccc;
  margin: 0 0 10px;
  height: 50px;
}
#header2 {order: 2;}
#header1 {order: 1;}
#header3 {order: 3;}
#header4 {order: 4;}
#header2:hover {
background-color: rgba(10,50,10,0.9);
}
#header2:active {
    background-color: rgba(0,0,0,0);
}
#header2:active ~ #header1,
#header2:hover ~ #header1 {
    background-color: rgba(0,0,0,0.8);
}
#header2:active ~ #header3,
#header2:hover ~ #header3 {
    background-color: rgba(50,10,10,0.8);
}
#header2:active ~ #header4,
#header2:hover ~ #header4 {
    background-color: rgba(10,10,50,0.8);
}
<div class="headers">
  <div id="header2"><a data-scroll id="link2" href="#header2content">Header 2</a></div>
  <div id="header1"><a data-scroll id="link1" href="#header1content">Header 1</a></div>
  <div id="header3"><a data-scroll id="link3" href="#header3content">Header 3</a></div>
  <div id="header4"><a data-scroll id="link4" href="#header4content">Header 4</a></div>
</div>