Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to animate background-color of an element on mouse hover using CSS?

Answer: Using CSS background and transition property

The CSS hover effects give us the ability to change the CSS property. The hover can let us change the background color also of any element.

In this tutorial, we will be learning about the properties used to change the background color of elements on hover.

The :hover class is used to select any element when the mouse is over it. We can change the color of the element on the hover by adding background property with hover class to the element. We can also add transition property to animate between the colors.

Example: Change background-color of an element on hover

Here, in this program, we have added a background color on the hover that will change the background color of the element when we hover the cursor over it. The transition property will slowly animate the background color to change.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
  button {
    color: black;
	font: bold 18px sans-serif;
    background: cyan;
  }
  button:hover {
    background: blue;
    -webkit-transition: background 3s; /* For Safari */
    transition: background 3s; /* For modern browsers */
	}  
</style>
</head>
<body>
   <h2> Change color on hover </h2>
   <button> Click here </button>
</body>
</html>

Output

Here is the output of the above example.

change background color on hover

Example: Change the color of a link on hover

Here is another example to change the background color of a link on hover.

Conclusion

In this tutorial, we have learned to change the background color of the element on hover. We used the background property to the element using the hover class. We can also change the color of HTML elements like buttons, links, etc.



About the author: