You can only do this if the element you want affected is preceded by the hovered element. In this case, if you want element .blockB
to be affected by the hover of .blockA
, you can use the general ~
or next element +
selector. However, if you want .blockA
to be affected by the hover on .blockB
you need to use Javascript, since there is not a preceding element selector in CSS
.blockA {
width: 64px;
height: 64px;
background-color: red;
}
.blockB {
width: 64px;
height: 64px;
background-color: orange;
transition: 0.5s ease-out 100ms;
}
/* General Sibling Selector */
.blockA:hover ~ .blockB {
background-color: blue;
}
.blockC {
width: 64px;
height: 64px;
background-color: red;
}
.blockD {
width: 64px;
height: 64px;
background-color: orange;
transition: 0.5s ease-out 100ms;
}
/* Next element selector */
.blockC:hover + .blockD {
background-color: blue;
}
<div class="blockA"></div>
<div class="blockB"></div>
<div class="blockC"></div>
<div class="blockD"></div>
If you want to also affect the previous element on hover, here is a snippet with the JS to handle that. We would need to add a class to the second .second
element to know what preceding element to affect on hover.
// Get all the elements with the class "second"
let second_elem = document.querySelectorAll('.second');
// This loops through each second_elem
second_elem.forEach(elem => {
// We are now adding an event listener - in this case when the mouse enters the element.
elem.addEventListener('mouseenter', (event) => {
// The event target is the element that is hovered. We get the immediate preceding element.
let prev_elem = event.target.previousElementSibling;
// Add the "hovered" class. In this case to blockA.
prev_elem.classList.add('hovered');
});
// Adds an event listener for when the mouse leaves the second element
elem.addEventListener('mouseleave', (event) => {
let prev_elem = event.target.previousElementSibling;
// remove the "hovered" class. In this case from blockA
prev_elem.classList.remove('hovered');
});
});
/* We can also make the JS event listeners into a function, but for this case, just keeping it simple. */
.blockA {
width: 64px;
height: 64px;
background-color: red;
transition: 0.5s ease-out 100ms;
}
.blockB {
width: 64px;
height: 64px;
background-color: orange;
transition: 0.5s ease-out 100ms;
}
/* Next element selector */
.blockA:hover+.blockB {
background-color: blue;
}
/* when the hovered class gets added by the JS */
.blockA.hovered {
background-color: green;
}
<div class="blockA"></div>
<div class="blockB second"></div>