How to change style of element "a" when element "b" is hovered? Actually there is couple of solutions for this problem using only CSS. In this text we will give you idea how to do it.
- Hover element #a to change background colour of element #b:
- if element #b comes after element #a in this example we can use+
operator:
#a:hover + #b{}
- Hover element #b to change background colour for element #a:
In this example we will use a little trick, actually we will hover over parent element but force the background colour of element #a (on hover) to be default colour
HTML
<div id="wrapper">
<div id="a"> el A </div>
<div id="b"> el B</div>
</div>
CSS
#wrapper{
display:inline-block;
}
#a,#b{
width:50px;
height:50px;
padding:5px;
color: white;
cursor:pointer;
float: left;
}
#a{
background-color:red;
}
#b{
background-color:blue;
}
#a:hover + #b{
background-color:green;
}
#wrapper:hover #a{
background-color:orange;
}
#a:hover{
background-color:red !important;
}
Here is the example on codepen:
hover element a - change element b
Another interesting example, would be using ::before and ::after selectors: