How can I force a hover to trigger another hover with CSS? What’s an example?
It depends on exactly what you want, so you can start with an example and say what you want to do instead.
You can’t actually trigger a hover to something else, but you can change something else while hovering elsewhere (depending on structure). For example, when you hover over a div, you can style the child elements while the parent is hovered. Alternatively, you can style the adjacent element, but lose the effect on the adjacent element as soon as you release the mouse (unlike child elements, which can stay). Always active while parent is hovered.
)
In CSS, you can use the ‘:hover’ and ‘:active’ pseudo-classes to make one hover trigger another. Here’s an example of how to do this:
HTML:
<div class="container">
<div class="hover-1">Hover 1</div>
<div class="hover-2">Hover 2</div>
</div>
CSS:
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.hover-1:hover + .hover-2 {
background-color: yellow;
}
.hover-2:active {
background-color: red;
}
In this example, when hovering over the “Hover 1” element, the “Hover 2” element will have a yellow background. Click on “Hover 2” and the background color will change to red.
Note that this method will only work if the second hover element is a sibling of the first hover element and is positioned immediately after the first. The “+” selector is used to select his second element that immediately follows the first.
No, you can’t trigger the hover state with something else, as already explained above.
As shown in my demo, you can style different elements based on hovering siblings. The demo is pretty much the same, but uses adjacent selectors that limit the scope to only the following elements:
As Paul says, you can “fake” activating hover states for siblings/descendants etc. You can (usually) do it both ways too.But it’s worth pointing out that it’s not actual Enable hover states on other elements. This can be an important difference for Javascript, etc.
1 like
Hi @zuhaybtaha210, welcome to the forums.
Just to let you know, you can format your code using A button in the menu at the top of the text editor.
This wraps the code at the tick start and end ``` your code here ```
this time i did it for you
1 like