Question:
Well basically, I have the following structure, where when hover
is activated on an element, the brothers on the right should be given a unique style, while the ones on the left should be styled differently. I currently have the same code working fine in JS to style the siblings to the left of the element in hover
, however, I feel annoyed that I can't do everything just with CSS, so the question, is it possible to select all siblings before the selected one 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>
Answer:
CSS doesn't have a selector that solves anteriority, but in your case a "double hover" can solve it (it 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>