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

How to change image on hover using CSS?

王林
Release: 2023-09-01 10:05:11
forward
1431 people have browsed it

如何使用 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?"> 
Copy after login

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");
} 
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template