Home  >  Article  >  Web Front-end  >  How to change image on hover using CSS?

How to change image on hover using CSS?

王林
王林forward
2023-09-01 10:05:111354browse

如何使用 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 to changing images on hover using CSS is to have two images you want to use: the How to change image on hover using CSS? image and the hover image. Make sure both images are saved on your website and that you know the URL of each image.

Add How to change image on hover using CSS? image to your HTML

Use the img tag and specify the source (src) of the image. For example -

<img src="How to change image on hover using CSS?-image.jpg" alt="How to change image on hover using CSS?"> 

Add a hover rule in 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

Using CSS to change images on hover is a simple and effective way to add extra engagement to your website. This is a great way to create an interactive experience for users that can help them stay on your site longer and increase their overall satisfaction.

The above is the detailed content of How to change image on hover using CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete