CSS get siblings before element?

2
Basically, I have the following structure, where when hover is enabled on an element, the right siblings should receive a unique style, while those on the left should receive another style. I currently have the same code working fine in JS to stylize the left siblings of the element in hover however, I feel bothered not to be able to do everything just with CSS, so the question is, can you select all siblings before selected using CSS ?

.main{
  width: 100%;
  height:50px;
}
.child{
  width:50px;
  height:50px;
  
  background-color:#F00;
  display: inline-block;
  margin-right: 5px;
}

.child:hover{
  background-color: #0F0;
}
/*define cor para todos os siblings depois deste*/
.child:hover ~ .child{
  background-color: #00F;
}
<div class="main">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
    
asked by anonymous 24.07.2018 / 23:51

2 answers

3

CSS has no selector that resolves precedence, but in your case a "double hover" can resolve (works in IE11, inclusive):

.main{
  width: 100%;
  height:50px;
}

.child{
  width:50px;
  height:50px;
  
  background-color:#F00;
  display: inline-block;
  margin-right: 5px;
}

.main:hover .child{         /* o hover no main aciona a mudança no resto */
  background-color: #FF0;
}

.main:hover .child:hover,
.child:hover{
  background-color: #0F0;
}

.child:hover ~ .child{
  background-color: #00F;
}

 
<div class="main">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
    
25.07.2018 / 01:34
2

I have a solution that can serve. But there are some holes, container has to be exactly the size of the children to be cool. You need to put a hover in the parent followed by a :hover:not() rule in the children.

You can see that now in the% of children they are divided into three parts, a color before the hover, a color in the element that has been hatched, and another color in the brother elements.

    .main{
      width: 250px;
      background-color:silver;
      display: flex;
    }
    .main:hover > .child:not(:hover) {
      background-color:#ff0;
    }
    .child{
      width:50px;
      height:50px;
      background-color:#f00;
      border: 1px solid black;

    }
    .child:hover{
      background-color: #0F0;
    }
    /*define cor para todos os siblings depois deste*/
    .child:hover ~ .child{
      background-color: #00F !important;
    }
    <div class="main">
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
    </div>
    
25.07.2018 / 01:22