Igor Simic
3 years ago

CSS: on hover change other element

How to change one element style when another is hovered? For example, we want to hover over element "a" and while this element is hovered we want to change element "b". This is possible, but there are some limitations.

1. Hover element #a to change background colour of element #b:
<div id="wrapper">
    <div id="a"> el A </div>
    <div id="b"> el B</div>
#a:hover + #b{
2. 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:
#wrapper:hover #a{

  background-color:red !important;

Here is the example on codepen:

Another interesting approach would be by using ::before or ::after  selectors: