How to show an element on hover using CSS?

Hover over me to display the below element!
Tada!, I am visible

To show an element or text on hover, we can use the display property with CSS :hover pseudo-class.

By default, we want the targeted element to remain hidden. This we can achieve by applying display: none; on it.

Now, whenever, we hover over its adjacent, we want to display it. To do that we have to apply display: block; inside the :hover pseudo-class.

Here is a complete working example:

Example:

div.source{
   background: springgreen;
   padding: 10px;
}
div.target{
   display: none;
   background: yellow;
   padding: 20px;
}
div.source:hover + div.target{
   display: block;
}

The div.source:hover + div.target represents that whenever we hover over a div having a class source, its adjacent div which have a class target must be displayed as a block.

See this image:

Show an element on hover using CSS

Hide an element on hover

If you want to do just reverse of the above i.e. you want to hide an element on hover, you can do this just by applying display: block; initially and display: none; on hover.

Here is a working example:

Example:

div.source{
   background: springgreen;
   padding: 10px;
}
div.target{
   display: block;
   background: yellow;
   padding: 20px;
}
div.source:hover + div.target{
   display: none;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.