How to Change Image on hover with CSS ?
Last Updated :
06 Mar, 2024
To change an image on hover with CSS, use the :hover pseudo-class on the image element and alter its properties, such as background-image or content, to display a different image when hovered over.
Here are some common approaches to changing the image on hover:
1. Using Background Image Swap:
In CSS, background image swap involves using the :hover pseudo-class on an element and changing its background-image property to a new image URL upon hover, providing a seamless transition effect and enhancing user interaction with the webpage.
Example: Here, we are swapping the background image of an element on hover using CSS. The initial image is set with background-image, and :hover pseudo-class changes it smoothly.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
How to Change Image on
Hover in CSS
</ title >
< style >
.sudo {
width: 230px;
height: 195px;
margin: 50px;
background-image: url(
background-size: cover;
transition: background-image 0.3s ease-in-out;
}
.sudo:hover {
background-image: url(
}
</ style >
</ head >
< body >
< h2 >GeeksForGeeks</ h2 >
< h2 >
changing image on
hover by Using Background Image Swap
</ h2 >
< div class = "sudo" ></ div >
</ body >
</ html >
|
Output:
Using Background Image Swap
2. Using Content Property:
The Content Property utilizes CSS’s ::before and ::after pseudo-elements to insert content before or after an element, often used for generating dynamic content or altering the appearance of elements.
Example: In this example we demonstrates changing an image on hover using the Content Property. The ::before pseudo-element is utilized to display different images before and after hover, providing a smooth transition effect.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >Change Image on Hover</ title >
< style >
.image-container {
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
}
.image-container::before {
content: url(
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transition: opacity 0.3s ease-in-out;
}
.image-container:hover::before {
content: url(
}
</ style >
</ head >
< body >
< h2 >GeeksForGeeks</ h2 >
< h2 >
changing image on
hover by Using Content Property
</ h2 >
< div class = "image-container" ></ div >
</ body >
</ html >
|
Output:
Using Content Property
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...