CSS HTML

How to make the hover effect on one element affect another

November 29, 2021

How to make the hover effect on one element affect another

In this article you will learn how to make the hover effect on one element affect another, through pure CSS and of course, quickly and easily!

hover effect on one element affect another cover

What’s up programmer, how are you? Let’s learn something new! 

The idea behind affecting an element other than the one we put the mouse over the hover is simple

We need to identify the hover element, as we normally do.

But following it, we put the class/id of the element that really needs to change the style, if it’s a child of the element.

For example if it is a ‘twin’, that is, on the same level, we must put a + between the selectors

That way we are able to achieve our goal, see an example:

<!DOCTYPE html>
<html>
 <head>
  <title>Efeito de hover em um elemento afetar outro</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div id="element"></div>
  <div id="hover-element"></div>
 </body>
</html>

We created two distinct elements, and the idea here will be to activate the hover in #hover-element by passing the mouse pointer over #element

So let’s go to CSS:

div {
 width: 50px;
 height: 50px;
 margin: 30px;
}

#elemento {
 background-color: red;
}

#elemento-hover {
 background-color: blue;
}

#elemento:hover + #elemento-hover {
 background-color: magenta;
}

In our case this will be return:

This was a case of tags at the same level, now let’s look at one with a hover on a parent tag, applying the effect to the child tag:

<!DOCTYPE html>
<html>
 <head>
  <title>Efeito de hover em um elemento afetar outro</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div>
   <p id="p-hover">Testando hover</p>
   <p>Este não vai ter hover</p>
  </div>
</body>
</html>

And now the CSS:

div {
 margin: 50px;
 width: 500px;
}

div:hover #p-hover {
 color: red;
 font-weight: bold;
 border-bottom: 2px dotted yellow;
 background-color: #000;
}

The result of hovering anywhere in the div is this:

And in this way we can enable hovering on one element and applying the style (CSS) on another! 

Conclusion

In this article we learned how to make the hover effect on one element affect another

First we need to identify the relatedness of the element that will activate the hover

Then create a CSS rule that activates the hover on the element that should activate it

Followed by how this element relates to the element that should change the style, if it’s a sibling/brother you can add a +, and so on.

Want to learn more about CSS? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x