- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change image on hover with CSS?
The "hover" pseudo-class is used to select and apply styles to an HTML element when a user hovers their mouse over it.
Changing an image on hover with CSS is a simple process that can add an extra layer of interactivity to the website. Here, we will learn step-by-step guide to changing an image on hover with CSS −
Prepare the images
The first step in changing an image on hover using CSS is to have the two images you want to use: the default image and the hover image. Make sure these are both saved on your website and that you know the URLs for each.
Add the default image to your HTML
Use the img tag and specify the source (src) of the image. For example −
<img src="default-image.jpg" alt="default">
Add a hover rule to your CSS
In the CSS file, we add a rule to change the image on hover. we will do this by targeting the div tag and specifying a :hover pseudo-class. For example −
img:hover { content: url("hover-image.jpg"); }
Example
Here is an example to change the image on hover using CSS.
<html> <head> <title>Change Image on Hover in CSS</title> <style> body{ text-align:center; } div { width: 250px; height: 195px; background: url("https://www.tutorialspoint.com/dip/images/black_and_white.jpg") norepeat; display: inline-block; } div:hover { background: url("https://www.tutorialspoint.com/dip/images/einstein.jpg") no-repeat; } </style> </head> <body> <h2>Change Image on Hover Using CSS</h2> <div class="card"></div> </body> </html>
Conclusion
To change an image on hover using CSS is a simple yet effective way to add an extra layer of engagement to the website. It is a great way to create an interactive experience for users, which can help to keep them on the site longer and increase their overall satisfaction.